﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Security;

using Bricks.Component.Utils;
using Bricks.Business.Models;
using Bricks.Business.Models.FlowProcess;
using Bricks.Site.Models;
using Bricks.Business.Data.Repositories.ScheduleManagement;
using System.Xml;
using Bricks.Business.Service;
using Bricks.Business.Models.ScheduleManagement;
using Bricks.Component.Data;
using Bricks.Site.Models.DBViewModel.Contract;


namespace ChiDao.Business.Service.Impl
{
    [Export(typeof(IMonthPlanService))]
    internal class MonthPlanService : IMonthPlanService
    {
        #region 属性
        [Import]
        protected IStatisticsItemMaintenanceRepository StatisticsItemMaintenanceRepository { get; set; }
        [Import]
        protected ITotalReviseRepository TotalReviseRepository { get; set; }
        [Import]
        protected ITotalReviseDetailsRepository TotalReviseDetailsRepository { get; set; }
        [Import]
        protected IYearPlanReviseRepository YearPlanReviseRepository { get; set; }
        [Import]
        protected IYearPlanReviseDetailsRepository YearPlanReviseDetailsRepository { get; set; }
        [Import]
        protected IMonthPlanRepository MonthPlanRepository { get; set; }
        [Import]
        protected IMonthPlanDetailsRepository MonthPlanDetailsRepository { get; set; }
        #endregion

        public class TempModel
        {
            //统计项ID
            public Guid StatisticsItemID { get; set; }

            //本月实际完成工程量:可用于本月计划、本年累计以及开工累计
            public string EngineeringNum { get; set; }

            //本月实际完成金额:可用于本月计划、本年累计以及开工累计
            public string MoneyNum { get; set; }
        }

        public IQueryable<MonthPlan> MonthPlans
        {
            get { return MonthPlanRepository.Entities; }
        }

        #region 公共私有函数
        //获取指定项目、合同类型和标段下总量维护最后修订金额
        private string GetTotalReviseMoney(Guid projectID, string contractType, Guid contractID)
        {
            string totalMoney = string.Empty;
            TotalRevise totalRevise = TotalReviseRepository.Entities.Where(t => t.ProjectID == projectID && t.ContractType == contractType && t.ContractID == contractID).OrderByDescending(t => t.ReviseDate).FirstOrDefault();
            if (totalRevise != null)
            {
                totalMoney = totalRevise.ReviseMoney;
            }
            return totalMoney;
        }

        //设置当前年月的上一个月
        private void SetLastYearAndMonth(string year, string month, ref string lastYear, ref string lastMonth)
        {
            if (!string.IsNullOrEmpty(year) && !string.IsNullOrEmpty(month))
            {
                lastYear = year;
                int monthNum = Convert.ToInt32(month);
                if (monthNum == 1)
                {
                    lastYear = (Convert.ToInt32(year) - 1).ToString();
                    lastMonth = "12";
                }
                else
                {
                    lastMonth = (monthNum - 1).ToString();
                }
            }
        }

        //获取月进度计划中上月月度计划审批完成的下月计划金额，为审批结束的取年计划中对应月计划数据
        private string GetLastMonthMoney(Guid projectID, string contractType, Guid contractID, string lastYear, string lastMonth, YearPlanRevise yearPlanRevise, string month)
        {
            string lastMonthMoney = "0";
            MonthPlan monthPlan = MonthPlanRepository.Entities.SingleOrDefault(m => m.ProjectID == projectID && m.ContractType == contractType && m.ContractID == contractID && m.Year == lastYear && m.Month == lastMonth);
            if (monthPlan != null && monthPlan.HandleState == "2")
            {
                lastMonthMoney = monthPlan.TotalNextMonthPlanMoneyNum;
            }
            else
            {
                if (yearPlanRevise != null)
                {
                    switch (month)
                    {
                        case "1":
                            lastMonthMoney = yearPlanRevise.JanuaryMoneyNum;
                            break;
                        case "2":
                            lastMonthMoney = yearPlanRevise.FebruaryMoneyNum;
                            break;
                        case "3":
                            lastMonthMoney = yearPlanRevise.MarchMoneyNum;
                            break;
                        case "4":
                            lastMonthMoney = yearPlanRevise.AprilMoneyNum;
                            break;
                        case "5":
                            lastMonthMoney = yearPlanRevise.MayMoneyNum;
                            break;
                        case "6":
                            lastMonthMoney = yearPlanRevise.JuneMoneyNum;
                            break;
                        case "7":
                            lastMonthMoney = yearPlanRevise.JulyMoneyNum;
                            break;
                        case "8":
                            lastMonthMoney = yearPlanRevise.AugustMoneyNum;
                            break;
                        case "9":
                            lastMonthMoney = yearPlanRevise.SeptemberMoneyNum;
                            break;
                        case "10":
                            lastMonthMoney = yearPlanRevise.OctoberMoneyNum;
                            break;
                        case "11":
                            lastMonthMoney = yearPlanRevise.NovemberMoneyNum;
                            break;
                        case "12":
                            lastMonthMoney = yearPlanRevise.DecemberMoneyNum;
                            break;
                    }
                }
            }
            return lastMonthMoney;
        }

        //获取本年和开工累计完成金额
        private void GetCumulativeCompletedMoney(Guid projectID, string contractType, Guid contractID, string year, string month, ref decimal currentYearCumulativeCompletedMoney, ref decimal constructionCompletedMoneyNum)
        {
            int yearNum = Convert.ToInt32(year);
            IQueryable<MonthPlan> lstMonthPlan = MonthPlanRepository.Entities.Where(m => m.ProjectID == projectID && m.ContractType == contractType && m.ContractID == contractID && ((m.Year.CompareTo(year) < 0) || (m.Year == year && m.Month.CompareTo(month) <= 0)));
            foreach (MonthPlan monthPlan in lstMonthPlan)
            {
                if (monthPlan.HandleState == "2")
                {
                    int monthPlanYearNum = Convert.ToInt32(monthPlan.Year);
                    if (!string.IsNullOrEmpty(monthPlan.TotalCurrentMonthActualCompletedMoneyNum))
                    {
                        if (yearNum == monthPlanYearNum)
                        {
                            currentYearCumulativeCompletedMoney = currentYearCumulativeCompletedMoney + Convert.ToDecimal(monthPlan.TotalCurrentMonthActualCompletedMoneyNum);
                            constructionCompletedMoneyNum = constructionCompletedMoneyNum + Convert.ToDecimal(monthPlan.TotalCurrentMonthActualCompletedMoneyNum);
                        }

                        if (yearNum > monthPlanYearNum)
                        {
                            constructionCompletedMoneyNum = constructionCompletedMoneyNum + Convert.ToDecimal(monthPlan.TotalCurrentMonthActualCompletedMoneyNum);
                        }
                    }
                }
            }
        }



        //获取月进度计划中上月月度计划审批完成的下月计划金额明细，为审批结束的取年计划中对应月计划数据明细
        private List<TempModel> GetLastMonthDetails(Guid projectID, string contractType, Guid contractID, string lastYear, string lastMonth, YearPlanRevise yearPlanRevise, string month)
        {
            List<TempModel> lstLastMonthDetail = new List<TempModel>();
            MonthPlan monthPlan = MonthPlanRepository.Entities.SingleOrDefault(m => m.ProjectID == projectID && m.ContractType == contractType && m.ContractID == contractID && m.Year == lastYear && m.Month == lastMonth);
            if (monthPlan != null && monthPlan.HandleState == "2")
            {
                IQueryable<MonthPlanDetails> lstMonthPlanDetail = MonthPlanDetailsRepository.Entities.Where(md => md.MonthPlanID == monthPlan.ID);
                foreach (MonthPlanDetails monthPlanDetails in lstMonthPlanDetail)
                {
                    lstLastMonthDetail.Add(new TempModel()
                    {
                        StatisticsItemID = monthPlanDetails.StatisticsItemID,
                        EngineeringNum = monthPlanDetails.NextMonthPlanEngineeringNum,
                        MoneyNum = monthPlanDetails.NextMonthPlanMoneyNum
                    });
                }
            }
            else
            {
                if (yearPlanRevise != null)
                {
                    IQueryable<YearPlanReviseDetails> lstYearPlanReviseDetail = YearPlanReviseDetailsRepository.Entities.Where(yrd => yrd.YearPlanReviseID == yearPlanRevise.ID);
                    foreach (YearPlanReviseDetails yearPlanReviseDetails in lstYearPlanReviseDetail)
                    {
                        switch (month)
                        {
                            case "1":
                                lstLastMonthDetail.Add(new TempModel()
                                {
                                    StatisticsItemID = yearPlanReviseDetails.StatisticsItemID,
                                    EngineeringNum = yearPlanReviseDetails.JanuaryEngineeringNum,
                                    MoneyNum = yearPlanReviseDetails.JanuaryMoneyNum
                                });
                                break;
                            case "2":
                                lstLastMonthDetail.Add(new TempModel()
                                {
                                    StatisticsItemID = yearPlanReviseDetails.StatisticsItemID,
                                    EngineeringNum = yearPlanReviseDetails.FebruaryEngineeringNum,
                                    MoneyNum = yearPlanReviseDetails.FebruaryMoneyNum
                                });
                                break;
                            case "3":
                                lstLastMonthDetail.Add(new TempModel()
                                {
                                    StatisticsItemID = yearPlanReviseDetails.StatisticsItemID,
                                    EngineeringNum = yearPlanReviseDetails.MarchEngineeringNum,
                                    MoneyNum = yearPlanReviseDetails.MarchMoneyNum
                                });
                                break;
                            case "4":
                                lstLastMonthDetail.Add(new TempModel()
                                {
                                    StatisticsItemID = yearPlanReviseDetails.StatisticsItemID,
                                    EngineeringNum = yearPlanReviseDetails.AprilEngineeringNum,
                                    MoneyNum = yearPlanReviseDetails.AprilMoneyNum
                                });
                                break;
                            case "5":
                                lstLastMonthDetail.Add(new TempModel()
                                {
                                    StatisticsItemID = yearPlanReviseDetails.StatisticsItemID,
                                    EngineeringNum = yearPlanReviseDetails.MayEngineeringNum,
                                    MoneyNum = yearPlanReviseDetails.MayMoneyNum
                                });
                                break;
                            case "6":
                                lstLastMonthDetail.Add(new TempModel()
                                {
                                    StatisticsItemID = yearPlanReviseDetails.StatisticsItemID,
                                    EngineeringNum = yearPlanReviseDetails.JuneEngineeringNum,
                                    MoneyNum = yearPlanReviseDetails.JuneMoneyNum
                                });
                                break;
                            case "7":
                                lstLastMonthDetail.Add(new TempModel()
                                {
                                    StatisticsItemID = yearPlanReviseDetails.StatisticsItemID,
                                    EngineeringNum = yearPlanReviseDetails.JulyEngineeringNum,
                                    MoneyNum = yearPlanReviseDetails.JulyMoneyNum
                                });
                                break;
                            case "8":
                                lstLastMonthDetail.Add(new TempModel()
                                {
                                    StatisticsItemID = yearPlanReviseDetails.StatisticsItemID,
                                    EngineeringNum = yearPlanReviseDetails.AugustEngineeringNum,
                                    MoneyNum = yearPlanReviseDetails.AugustMoneyNum
                                });
                                break;
                            case "9":
                                lstLastMonthDetail.Add(new TempModel()
                                {
                                    StatisticsItemID = yearPlanReviseDetails.StatisticsItemID,
                                    EngineeringNum = yearPlanReviseDetails.SeptemberEngineeringNum,
                                    MoneyNum = yearPlanReviseDetails.SeptemberMoneyNum
                                });
                                break;
                            case "10":
                                lstLastMonthDetail.Add(new TempModel()
                                {
                                    StatisticsItemID = yearPlanReviseDetails.StatisticsItemID,
                                    EngineeringNum = yearPlanReviseDetails.OctoberEngineeringNum,
                                    MoneyNum = yearPlanReviseDetails.OctoberMoneyNum
                                });
                                break;
                            case "11":
                                lstLastMonthDetail.Add(new TempModel()
                                {
                                    StatisticsItemID = yearPlanReviseDetails.StatisticsItemID,
                                    EngineeringNum = yearPlanReviseDetails.NovemberEngineeringNum,
                                    MoneyNum = yearPlanReviseDetails.NovemberMoneyNum
                                });
                                break;
                            case "12":
                                lstLastMonthDetail.Add(new TempModel()
                                {
                                    StatisticsItemID = yearPlanReviseDetails.StatisticsItemID,
                                    EngineeringNum = yearPlanReviseDetails.DecemberEngineeringNum,
                                    MoneyNum = yearPlanReviseDetails.DecemberMoneyNum
                                });
                                break;
                        }
                    }
                }
            }
            return lstLastMonthDetail;
        }

        //获取本年和开工累计完成金额明细
        private void GetCumulativeCompletedDetails(Guid projectID, string contractType, Guid contractID, string year, string month, List<TempModel> lstCurrentYearCumulativeCompleted, List<TempModel> lstConstructionCompleted)
        {
            int yearNum = Convert.ToInt32(year);
            IQueryable<MonthPlan> lstMonthPlan = MonthPlanRepository.Entities.Where(m => m.ProjectID == projectID && m.ContractType == contractType && m.ContractID == contractID && ((m.Year.CompareTo(year) < 0) || (m.Year == year && m.Month.CompareTo(month) <= 0)));
            foreach (MonthPlan monthPlan in lstMonthPlan)
            {
                if (monthPlan.HandleState == "2")
                {
                    int monthPlanYearNum = Convert.ToInt32(monthPlan.Year);
                    //获取月度计划明细
                    IQueryable<MonthPlanDetails> lstMonthPlanDetail = MonthPlanDetailsRepository.Entities.Where(md => md.MonthPlanID == monthPlan.ID);
                    if (yearNum == monthPlanYearNum)
                    {
                        SetTempModelForCumulativeCompleted(lstMonthPlanDetail, lstCurrentYearCumulativeCompleted);
                        SetTempModelForCumulativeCompleted(lstMonthPlanDetail, lstConstructionCompleted);
                    }
                    if (yearNum > monthPlanYearNum)
                    {
                        foreach (MonthPlanDetails monthPlanDetails in lstMonthPlanDetail)
                        {
                            SetTempModelForCumulativeCompleted(lstMonthPlanDetail, lstConstructionCompleted);
                        }
                    }
                }
            }
        }

        //设置本年或者开工累计明细列表
        private void SetTempModelForCumulativeCompleted(IQueryable<MonthPlanDetails> lstMonthPlanDetail, List<TempModel> lstCumulativeCompleted)
        {
            foreach (MonthPlanDetails monthPlanDetails in lstMonthPlanDetail)
            {
                StatisticsItemMaintenance statisticsItemMaintenance = StatisticsItemMaintenanceRepository.Entities.Single(s => s.ID == monthPlanDetails.StatisticsItemID);
                if (statisticsItemMaintenance != null)
                {
                    TempModel exists = lstCumulativeCompleted.SingleOrDefault(t => t.StatisticsItemID == monthPlanDetails.StatisticsItemID);
                    if (exists == null)
                    {
                        lstCumulativeCompleted.Add(new TempModel()
                        {
                            StatisticsItemID = monthPlanDetails.StatisticsItemID,
                            EngineeringNum = monthPlanDetails.CurrentMonthActualCompletedEngineeringNum,
                            MoneyNum = monthPlanDetails.CurrentMonthActualCompletedMoneyNum
                        });
                    }
                    else
                    {
                        exists.EngineeringNum = CountEngineeringOrMoneyNumForDetails(monthPlanDetails.CurrentMonthActualCompletedEngineeringNum, exists.EngineeringNum);
                        exists.MoneyNum = CountEngineeringOrMoneyNumForDetails(monthPlanDetails.CurrentMonthActualCompletedMoneyNum, exists.MoneyNum);
                    }
                }
            }
        }

        //统计总量维护各个标段修订明细列表
        private void TotalTempModelForTotalReviseDetail(List<TotalReviseDetails> lstTotalReviseDetailForOneContract, List<TempModel> lstTotalReviseDetail)
        {
            foreach (TotalReviseDetails totalReviseDetails in lstTotalReviseDetailForOneContract)
            {
                StatisticsItemMaintenance statisticsItemMaintenance = StatisticsItemMaintenanceRepository.Entities.Single(s => s.ID == totalReviseDetails.StatisticsItemID);
                if (statisticsItemMaintenance != null)
                {
                    TempModel exists = lstTotalReviseDetail.SingleOrDefault(t => t.StatisticsItemID == totalReviseDetails.StatisticsItemID);
                    if (exists == null)
                    {
                        lstTotalReviseDetail.Add(new TempModel()
                        {
                            StatisticsItemID = totalReviseDetails.StatisticsItemID,
                            EngineeringNum = totalReviseDetails.EngineeringNum,
                            MoneyNum = totalReviseDetails.MoneyNum
                        });
                    }
                    else
                    {
                        exists.EngineeringNum = CountEngineeringOrMoneyNumForDetails(totalReviseDetails.EngineeringNum, exists.EngineeringNum);
                        exists.MoneyNum = CountEngineeringOrMoneyNumForDetails(totalReviseDetails.MoneyNum, exists.MoneyNum);
                    }
                }
            }
        }

        //统计年度计划各个标段修订明细列表
        private void TotalTempModelForYearPlanReviseDetail(List<YearPlanReviseDetails> lstYearPlanReviseDetailForOneContract, List<TempModel> lstYearPlanReviseDetail)
        {
            foreach (YearPlanReviseDetails yearPlanReviseDetails in lstYearPlanReviseDetailForOneContract)
            {
                StatisticsItemMaintenance statisticsItemMaintenance = StatisticsItemMaintenanceRepository.Entities.Single(s => s.ID == yearPlanReviseDetails.StatisticsItemID);
                if (statisticsItemMaintenance != null)
                {
                    TempModel exists = lstYearPlanReviseDetail.SingleOrDefault(t => t.StatisticsItemID == yearPlanReviseDetails.StatisticsItemID);
                    if (exists == null)
                    {
                        lstYearPlanReviseDetail.Add(new TempModel()
                        {
                            StatisticsItemID = yearPlanReviseDetails.StatisticsItemID,
                            EngineeringNum = yearPlanReviseDetails.TotalEngineeringNum,
                            MoneyNum = yearPlanReviseDetails.TotalMoneyNum
                        });
                    }
                    else
                    {
                        exists.EngineeringNum = CountEngineeringOrMoneyNumForDetails(yearPlanReviseDetails.TotalEngineeringNum, exists.EngineeringNum);
                        exists.MoneyNum = CountEngineeringOrMoneyNumForDetails(yearPlanReviseDetails.TotalMoneyNum, exists.MoneyNum);
                    }
                }
            }
        }

        //统计月度计划各个标段修订明细列表
        private void TotalTempModelForMonthPlanDetail(IQueryable<MonthPlanDetails> lstMonthPlanDetailForOneContract, List<MonthPlanDetails> lstMonthPlanDetail)
        {
            foreach (MonthPlanDetails monthPlanDetails in lstMonthPlanDetailForOneContract)
            {
                StatisticsItemMaintenance statisticsItemMaintenance = StatisticsItemMaintenanceRepository.Entities.Single(s => s.ID == monthPlanDetails.StatisticsItemID);
                if (statisticsItemMaintenance != null)
                {
                    MonthPlanDetails exists = lstMonthPlanDetail.SingleOrDefault(t => t.StatisticsItemID == monthPlanDetails.StatisticsItemID);
                    if (exists == null)
                    {
                        lstMonthPlanDetail.Add(monthPlanDetails.CopyTo<MonthPlanDetails>());
                    }
                    else
                    {
                        exists.CurrentMonthActualCompletedEngineeringNum = CountEngineeringOrMoneyNumForDetails(monthPlanDetails.CurrentMonthActualCompletedEngineeringNum, exists.CurrentMonthActualCompletedEngineeringNum);
                        exists.CurrentMonthActualCompletedMoneyNum = CountEngineeringOrMoneyNumForDetails(monthPlanDetails.CurrentMonthActualCompletedMoneyNum, exists.CurrentMonthActualCompletedMoneyNum);
                        exists.NextMonthPlanEngineeringNum = CountEngineeringOrMoneyNumForDetails(monthPlanDetails.NextMonthPlanEngineeringNum, exists.NextMonthPlanEngineeringNum);
                        exists.NextMonthPlanMoneyNum = CountEngineeringOrMoneyNumForDetails(monthPlanDetails.NextMonthPlanMoneyNum, exists.NextMonthPlanMoneyNum);
                    }
                }
            }
        }

        //统计上月计划、本年或者开工累计各个标段修订明细列表
        private void TotalTempModel(List<TempModel> lstDetailForOneContract, List<TempModel> lstDetail)
        {
            foreach (TempModel tempModel in lstDetailForOneContract)
            {
                StatisticsItemMaintenance statisticsItemMaintenance = StatisticsItemMaintenanceRepository.Entities.Single(s => s.ID == tempModel.StatisticsItemID);
                if (statisticsItemMaintenance != null)
                {
                    TempModel exists = lstDetail.SingleOrDefault(t => t.StatisticsItemID == tempModel.StatisticsItemID);
                    if (exists == null)
                    {
                        lstDetail.Add(new TempModel()
                        {
                            StatisticsItemID = tempModel.StatisticsItemID,
                            EngineeringNum = tempModel.EngineeringNum,
                            MoneyNum = tempModel.MoneyNum
                        });
                    }
                    else
                    {
                        exists.EngineeringNum = CountEngineeringOrMoneyNumForDetails(tempModel.EngineeringNum, exists.EngineeringNum);
                        exists.MoneyNum = CountEngineeringOrMoneyNumForDetails(tempModel.MoneyNum, exists.MoneyNum);
                    }
                }
            }
        }

        //统计工程量或者金额
        private string CountEngineeringOrMoneyNumForDetails(string engineeringOrMoneyNum, string totalEngineeringOrMoneyNum)
        {
            if (!string.IsNullOrEmpty(engineeringOrMoneyNum))
            {
                if (string.IsNullOrEmpty(totalEngineeringOrMoneyNum))
                {
                    totalEngineeringOrMoneyNum = engineeringOrMoneyNum;
                }
                else
                {
                    if (totalEngineeringOrMoneyNum.Contains('/'))
                    {
                        string[] totalEngineeringOrMoneyNumArr = totalEngineeringOrMoneyNum.Split('/');
                        string[] engineeringOrMoneyNumArr = engineeringOrMoneyNum.Split('/');
                        if (engineeringOrMoneyNumArr.Length == 2)
                        {
                            totalEngineeringOrMoneyNum = (Convert.ToDecimal(totalEngineeringOrMoneyNumArr[0]) + Convert.ToDecimal(engineeringOrMoneyNumArr[0])).ToString() + "/" + (Convert.ToDecimal(totalEngineeringOrMoneyNumArr[1]) + Convert.ToDecimal(engineeringOrMoneyNumArr[1])).ToString();
                        }
                        else if (engineeringOrMoneyNumArr.Length == 1)
                        {
                            totalEngineeringOrMoneyNum = (Convert.ToDecimal(totalEngineeringOrMoneyNumArr[0]) + Convert.ToDecimal(engineeringOrMoneyNumArr[0])).ToString() + "/" + totalEngineeringOrMoneyNumArr[1];
                        }
                    }
                    else
                    {
                        string[] engineeringOrMoneyNumArr = engineeringOrMoneyNum.Split('/');
                        if (engineeringOrMoneyNumArr.Length == 1)
                        {
                            totalEngineeringOrMoneyNum = (Convert.ToDecimal(totalEngineeringOrMoneyNum) + Convert.ToDecimal(engineeringOrMoneyNum)).ToString();
                        }
                        else if (engineeringOrMoneyNumArr.Length == 2)
                        {
                            totalEngineeringOrMoneyNum = (Convert.ToDecimal(totalEngineeringOrMoneyNum) + Convert.ToDecimal(engineeringOrMoneyNumArr[0])).ToString() + "/" + engineeringOrMoneyNumArr[1];
                        }
                    }
                }
            }
            return totalEngineeringOrMoneyNum;
        }

        //获取父统计项的名称
        private string GetParentStatisticsItemName(Guid? PID)
        {
            string parentStatisticsItemName = string.Empty;
            StatisticsItemMaintenance parentStatisticsItemMaintenance = StatisticsItemMaintenanceRepository.Entities.SingleOrDefault(s => s.ID == PID);
            if (parentStatisticsItemMaintenance != null)
            {
                parentStatisticsItemName = parentStatisticsItemMaintenance.StatisticsItemName;
            }
            return parentStatisticsItemName;
        }

        //计算百分比
        private string CountProportion(string num, string totalNum)
        {
            string proportion = string.Empty;
            if (!string.IsNullOrEmpty(totalNum))
            {
                string totalNumTemp = totalNum;
                if (totalNum.Contains('/'))
                {
                    totalNumTemp = totalNum.Split('/')[0];
                }
                string numTemp = num;
                if (num.Contains('/'))
                {
                    numTemp = num.Split('/')[0];
                }
                if (totalNumTemp != "0" && numTemp != "0")
                {
                    proportion = Math.Round(Convert.ToDecimal(numTemp) * 100 / Convert.ToDecimal(totalNumTemp), 1).ToString() + "%";
                }
            }
            return proportion;
        }


        //为统计分析获取最大的最大的月
        private string GetMaxMonth(List<string> lstMonth)
        {
            string maxMonth = "1";
            if (lstMonth.Count > 0)
            {
                foreach (string month in lstMonth)
                {
                    if (month.CompareTo(maxMonth) > 0)
                    {
                        maxMonth = month;
                    }
                }
            }
            return maxMonth;
        }

        //为统计分析累加各个月的上月计划明细
        private void TotalSelectMonthForLastMonthDetail(List<TempModel> lstTotalDetail, List<TempModel> lstOneMonthDetail)
        {
            foreach (TempModel tempModel in lstOneMonthDetail)
            {
                TempModel exists = lstTotalDetail.SingleOrDefault(t => t.StatisticsItemID == tempModel.StatisticsItemID);
                if (exists == null)
                {
                    lstTotalDetail.Add(tempModel.CopyTo<TempModel>());
                }
                else
                {
                    exists.EngineeringNum = CountEngineeringOrMoneyNumForDetails(tempModel.EngineeringNum, exists.EngineeringNum);
                    exists.MoneyNum = CountEngineeringOrMoneyNumForDetails(tempModel.MoneyNum, exists.MoneyNum);
                }
            }
        }

        //为统计分析累加各个月的本月实际完成
        private void TotalSelectMonthForMonthPlanDetail(List<MonthPlanDetails> lstTotalDetail, List<MonthPlanDetails> lstOneMonthDetail)
        {
            foreach (MonthPlanDetails monthPlanDetails in lstOneMonthDetail)
            {
                MonthPlanDetails exists = lstTotalDetail.SingleOrDefault(t => t.StatisticsItemID == monthPlanDetails.StatisticsItemID);
                if (exists == null)
                {
                    lstTotalDetail.Add(monthPlanDetails.CopyTo<MonthPlanDetails>());
                }
                else
                {
                    exists.CurrentMonthActualCompletedEngineeringNum = CountEngineeringOrMoneyNumForDetails(monthPlanDetails.CurrentMonthActualCompletedEngineeringNum, exists.CurrentMonthActualCompletedEngineeringNum);
                    exists.CurrentMonthActualCompletedMoneyNum = CountEngineeringOrMoneyNumForDetails(monthPlanDetails.CurrentMonthActualCompletedMoneyNum, exists.CurrentMonthActualCompletedMoneyNum);
                }
            }
        }
        #endregion

        #region 主界面加载
        public List<MonthPlanView> GetMonthPlanList(Guid projectID, string contractType, Guid contractID)
        {
            //获取总金额
            string totalMoney = GetTotalReviseMoney(projectID, contractType, contractID);

            //获取月度计划数据
            List<MonthPlanView> lstMonthPlanView = new List<MonthPlanView>();
            var queryData = from mp in MonthPlanRepository.Entities
                            where mp.ProjectID == projectID && mp.ContractType == contractType && mp.ContractID == contractID
                            orderby mp.Year, mp.Month descending
                            select mp;
            foreach (var item in queryData)
            {
                MonthPlanView monthPlanView = new MonthPlanView();
                monthPlanView.ID = item.ID;
                monthPlanView.FlowCode = item.FlowCode;
                monthPlanView.ProjectID = item.ProjectID;
                monthPlanView.ContractType = item.ContractType;
                monthPlanView.ContractID = item.ContractID;
                monthPlanView.Year = item.Year;
                monthPlanView.Month = item.Month;
                monthPlanView.StatisticalCycle = item.Year + "年" + item.Month + "月";
                monthPlanView.Unit = item.Unit;
                monthPlanView.TotalMoneyNum = totalMoney;

                YearPlanRevise yearPlanRevise = YearPlanReviseRepository.Entities.Where(yr => yr.ProjectID == projectID && yr.ContractType == contractType && yr.ContractID == contractID && yr.StatisticalCycle == item.Year).OrderByDescending(yr => yr.ReviseDate).FirstOrDefault();
                if (yearPlanRevise != null)
                {
                    monthPlanView.YearPlanMoneyNum = yearPlanRevise.ReviseMoney == "0" ? string.Empty : yearPlanRevise.ReviseMoney;
                }

                string lastYear = string.Empty;
                string lastMonth = string.Empty;
                SetLastYearAndMonth(item.Year, item.Month, ref lastYear, ref lastMonth);
                string currentMonthPlanMoneyNum = GetLastMonthMoney(projectID, contractType, contractID, lastYear, lastMonth, yearPlanRevise, item.Month);
                monthPlanView.CurrentMonthPlanMoneyNum = currentMonthPlanMoneyNum == "0" ? string.Empty : currentMonthPlanMoneyNum;

                monthPlanView.CurrentMonthActualCompletedMoneyNum = item.TotalCurrentMonthActualCompletedMoneyNum;
                if (!string.IsNullOrEmpty(monthPlanView.CurrentMonthActualCompletedMoneyNum))
                {
                    if (!string.IsNullOrEmpty(totalMoney))
                    {
                        monthPlanView.CurrentMonthActualCompletedTotalProportion = Math.Round(Convert.ToDecimal(monthPlanView.CurrentMonthActualCompletedMoneyNum) * 100 / Convert.ToDecimal(totalMoney), 1).ToString() + "%";
                    }
                    if (!string.IsNullOrEmpty(monthPlanView.YearPlanMoneyNum))
                    {
                        monthPlanView.CurrentMonthActualCompletedYearProportion = Math.Round(Convert.ToDecimal(monthPlanView.CurrentMonthActualCompletedMoneyNum) * 100 / Convert.ToDecimal(monthPlanView.YearPlanMoneyNum), 1).ToString() + "%";
                    }
                    if (!string.IsNullOrEmpty(monthPlanView.CurrentMonthPlanMoneyNum))
                    {
                        monthPlanView.CurrentMonthActualCompletedMonthProportion = Math.Round(Convert.ToDecimal(monthPlanView.CurrentMonthActualCompletedMoneyNum) * 100 / Convert.ToDecimal(monthPlanView.CurrentMonthPlanMoneyNum), 1).ToString() + "%";
                    }
                }

                decimal currentYearCumulativeCompletedMoney = 0;
                decimal constructionCompletedMoneyNum = 0;
                GetCumulativeCompletedMoney(projectID, contractType, contractID, item.Year, item.Month, ref currentYearCumulativeCompletedMoney, ref constructionCompletedMoneyNum);
                monthPlanView.CurrentYearCumulativeCompletedMoneyNum = currentYearCumulativeCompletedMoney == 0 ? string.Empty : currentYearCumulativeCompletedMoney.ToString();
                if (!string.IsNullOrEmpty(monthPlanView.CurrentYearCumulativeCompletedMoneyNum))
                {
                    if (!string.IsNullOrEmpty(totalMoney))
                    {
                        monthPlanView.CurrentYearCumulativeCompletedTotalProportion = Math.Round(Convert.ToDecimal(monthPlanView.CurrentYearCumulativeCompletedMoneyNum) * 100 / Convert.ToDecimal(totalMoney), 1).ToString() + "%";
                    }
                    if (!string.IsNullOrEmpty(monthPlanView.YearPlanMoneyNum))
                    {
                        monthPlanView.CurrentYearCumulativeCompletedYearProportion = Math.Round(Convert.ToDecimal(monthPlanView.CurrentYearCumulativeCompletedMoneyNum) * 100 / Convert.ToDecimal(monthPlanView.YearPlanMoneyNum), 1).ToString() + "%";
                    }
                }

                monthPlanView.ConstructionCompletedMoneyNum = constructionCompletedMoneyNum == 0 ? string.Empty : constructionCompletedMoneyNum.ToString();
                if (!string.IsNullOrEmpty(monthPlanView.ConstructionCompletedMoneyNum))
                {
                    if (!string.IsNullOrEmpty(totalMoney))
                    {
                        monthPlanView.ConstructionCompletedTotalProportion = Math.Round(Convert.ToDecimal(monthPlanView.ConstructionCompletedMoneyNum) * 100 / Convert.ToDecimal(totalMoney), 1).ToString() + "%";
                    }
                }

                monthPlanView.NextMonthPlanMoneyNum = item.TotalNextMonthPlanMoneyNum;
                if (!string.IsNullOrEmpty(monthPlanView.NextMonthPlanMoneyNum))
                {

                    if (!string.IsNullOrEmpty(monthPlanView.YearPlanMoneyNum))
                    {
                        monthPlanView.NextMonthPlanYearProportion = Math.Round(Convert.ToDecimal(monthPlanView.NextMonthPlanMoneyNum) * 100 / Convert.ToDecimal(monthPlanView.YearPlanMoneyNum), 1).ToString() + "%";
                    }
                }
                lstMonthPlanView.Add(monthPlanView);
            }
            return lstMonthPlanView.OrderByDescending(mp => mp.Year).ThenByDescending(mp => mp.Month).ToList();
        }

        public List<MonthPlanDetailsView> GetMonthPlanDetailList(Guid projectID, string contractType, Guid contractID, string year, string month, Guid monthPlanID)
        {
            //获取总量维护修订ID
            Guid reviseID = GuidHelper.NewGuid();
            TotalRevise totalRevise = TotalReviseRepository.Entities.Where(t => t.ProjectID == projectID && t.ContractType == contractType && t.ContractID == contractID).OrderByDescending(t => t.ReviseDate).FirstOrDefault();
            if (totalRevise != null)
            {
                reviseID = totalRevise.ID;
            }

            //获取总量维护修订明细
            var queryTotalReviseDetails = from tr in TotalReviseDetailsRepository.Entities
                                          where tr.TotalReviseID == reviseID
                                          select tr;

            //获取年度计划修订ID
            Guid yearPlanReviseID = GuidHelper.NewGuid();
            YearPlanRevise yearPlanRevise = YearPlanReviseRepository.Entities.Where(yr => yr.ProjectID == projectID && yr.ContractType == contractType && yr.ContractID == contractID && yr.StatisticalCycle == year).OrderByDescending(yr => yr.ReviseDate).FirstOrDefault();
            if (yearPlanRevise != null)
            {
                yearPlanReviseID = yearPlanRevise.ID;
            }

            //获取年度计划修订明细
            var queryYearPlanReviseDetails = from yrd in YearPlanReviseDetailsRepository.Entities
                                             where yrd.YearPlanReviseID == yearPlanReviseID
                                             select yrd;

            //设置当前年月的上一个月
            string lastYear = string.Empty;
            string lastMonth = string.Empty;
            SetLastYearAndMonth(year, month, ref lastYear, ref lastMonth);

            //获取上月计划明细
            List<TempModel> lstLastMonthDetail = GetLastMonthDetails(projectID, contractType, contractID, lastYear, lastMonth, yearPlanRevise, month);


            //获取月度计划明细
            var queryMonthPlanDetails = from md in MonthPlanDetailsRepository.Entities
                                        where md.MonthPlanID == monthPlanID
                                        select md;

            //获取本年累计和开工累计
            List<TempModel> lstCurrentYearCumulativeCompleted = new List<TempModel>();
            List<TempModel> lstConstructionCompleted = new List<TempModel>();
            GetCumulativeCompletedDetails(projectID, contractType, contractID, year, month, lstCurrentYearCumulativeCompleted, lstConstructionCompleted);

            //获取连接查询数据
            var queryData = from s in StatisticsItemMaintenanceRepository.Entities.ToList()
                            join td in queryTotalReviseDetails
                            on s.ID equals td.StatisticsItemID into joinedEmpTD
                            from tempTD in joinedEmpTD.DefaultIfEmpty()

                            join yd in queryYearPlanReviseDetails
                            on s.ID equals yd.StatisticsItemID into joinedEmpYD
                            from tempYD in joinedEmpYD.DefaultIfEmpty()

                            join lmd in lstLastMonthDetail
                            on s.ID equals lmd.StatisticsItemID into joinedEmpLMD
                            from tempLMD in joinedEmpLMD.DefaultIfEmpty()

                            join md in queryMonthPlanDetails
                            on s.ID equals md.StatisticsItemID into joinedEmpMD
                            from tempMD in joinedEmpMD.DefaultIfEmpty()

                            join crc in lstCurrentYearCumulativeCompleted
                            on s.ID equals crc.StatisticsItemID into joinedEmpCRC
                            from tempCRC in joinedEmpCRC.DefaultIfEmpty()

                            join cc in lstConstructionCompleted
                            on s.ID equals cc.StatisticsItemID into joinedEmpCC
                            from tempCC in joinedEmpCC.DefaultIfEmpty()

                            where s.IsParent == false && s.ProjectID == projectID && s.ContractType == contractType
                            orderby s.OrderNo
                            select new
                            {
                                StatisticsItemID = s.ID,
                                s.StatisticsItemName,
                                s.PID,
                                s.EngineeringUnit,
                                s.MoneyUnit,
                                EngineeringNum = tempTD == null ? string.Empty : tempTD.EngineeringNum,
                                MoneyNum = tempTD == null ? string.Empty : tempTD.MoneyNum,
                                YearPlanEngineeringNum = tempYD == null ? string.Empty : tempYD.TotalEngineeringNum,
                                YearPlanMoneyNum = tempYD == null ? string.Empty : tempYD.TotalMoneyNum,
                                CurrentMonthPlanEngineeringNum = tempLMD == null ? string.Empty : tempLMD.EngineeringNum,
                                CurrentMonthPlanMoneyNum = tempLMD == null ? string.Empty : tempLMD.MoneyNum,
                                ID = tempMD == null ? GuidHelper.NewGuid() : tempMD.ID,
                                CurrentMonthActualCompletedEngineeringNum = tempMD == null ? string.Empty : tempMD.CurrentMonthActualCompletedEngineeringNum,
                                CurrentMonthActualCompletedMoneyNum = tempMD == null ? string.Empty : tempMD.CurrentMonthActualCompletedMoneyNum,
                                NextMonthPlanEngineeringNum = tempMD == null ? string.Empty : tempMD.NextMonthPlanEngineeringNum,
                                NextMonthPlanMoneyNum = tempMD == null ? string.Empty : tempMD.NextMonthPlanMoneyNum,
                                CurrentYearCumulativeCompletedEngineeringNum = tempCRC == null ? string.Empty : tempCRC.EngineeringNum,
                                CurrentYearCumulativeCompletedMoneyNum = tempCRC == null ? string.Empty : tempCRC.MoneyNum,
                                ConstructionCompletedEngineeringNum = tempCC == null ? string.Empty : tempCC.EngineeringNum,
                                ConstructionCompletedMoneyNum = tempCC == null ? string.Empty : tempCC.MoneyNum
                            };

            List<MonthPlanDetailsView> lstMonthPlanDetailsView = new List<MonthPlanDetailsView>();
            foreach (var item in queryData)
            {
                string parentStatisticsItemName = item.StatisticsItemName;
                if (item.PID != null)
                {
                    parentStatisticsItemName = GetParentStatisticsItemName(item.PID);
                }

                if (!string.IsNullOrEmpty(item.EngineeringUnit))
                {
                    MonthPlanDetailsView monthPlanDetailsView = new MonthPlanDetailsView();
                    monthPlanDetailsView.ID = item.ID;
                    monthPlanDetailsView.StatisticsItemID = item.StatisticsItemID;
                    monthPlanDetailsView.StatisticsItemName = item.StatisticsItemName;
                    monthPlanDetailsView.ParentStatisticsItemName = parentStatisticsItemName;
                    monthPlanDetailsView.Unit = item.EngineeringUnit;
                    monthPlanDetailsView.TotalAmount = item.EngineeringNum;
                    monthPlanDetailsView.YearPlanAmount = item.YearPlanEngineeringNum;
                    monthPlanDetailsView.CurrentMonthPlanAmount = item.CurrentMonthPlanEngineeringNum;

                    monthPlanDetailsView.CurrentMonthActualCompletedAmount = item.CurrentMonthActualCompletedEngineeringNum;
                    if (!string.IsNullOrEmpty(item.CurrentMonthActualCompletedEngineeringNum))
                    {
                        monthPlanDetailsView.CurrentMonthActualCompletedTotalProportion = CountProportion(item.CurrentMonthActualCompletedEngineeringNum, item.EngineeringNum);
                        monthPlanDetailsView.CurrentMonthActualCompletedYearProportion = CountProportion(item.CurrentMonthActualCompletedEngineeringNum, item.YearPlanEngineeringNum);
                        monthPlanDetailsView.CurrentMonthActualCompletedMonthProportion = CountProportion(item.CurrentMonthActualCompletedEngineeringNum, item.CurrentMonthPlanEngineeringNum);
                    }

                    monthPlanDetailsView.CurrentYearCumulativeCompletedAmount = item.CurrentYearCumulativeCompletedEngineeringNum;
                    if (!string.IsNullOrEmpty(item.CurrentYearCumulativeCompletedEngineeringNum))
                    {
                        monthPlanDetailsView.CurrentYearCumulativeCompletedTotalProportion = CountProportion(item.CurrentYearCumulativeCompletedEngineeringNum, item.EngineeringNum);
                        monthPlanDetailsView.CurrentYearCumulativeCompletedYearProportion = CountProportion(item.CurrentYearCumulativeCompletedEngineeringNum, item.YearPlanEngineeringNum);
                    }

                    monthPlanDetailsView.ConstructionCompletedAmount = item.ConstructionCompletedEngineeringNum;
                    if (!string.IsNullOrEmpty(item.ConstructionCompletedEngineeringNum))
                    {
                        monthPlanDetailsView.ConstructionCompletedTotalProportion = CountProportion(item.ConstructionCompletedEngineeringNum, item.EngineeringNum);
                    }

                    monthPlanDetailsView.NextMonthPlanAmount = item.NextMonthPlanEngineeringNum;
                    if (!string.IsNullOrEmpty(item.NextMonthPlanEngineeringNum))
                    {
                        monthPlanDetailsView.NextMonthPlanYearProportion = CountProportion(item.NextMonthPlanEngineeringNum, item.YearPlanEngineeringNum);
                    }

                    lstMonthPlanDetailsView.Add(monthPlanDetailsView);
                }

                if (!string.IsNullOrEmpty(item.MoneyUnit))
                {
                    MonthPlanDetailsView monthPlanDetailsView = new MonthPlanDetailsView();
                    monthPlanDetailsView.ID = item.ID;
                    monthPlanDetailsView.StatisticsItemID = item.StatisticsItemID;
                    monthPlanDetailsView.StatisticsItemName = item.StatisticsItemName;
                    monthPlanDetailsView.ParentStatisticsItemName = parentStatisticsItemName;
                    monthPlanDetailsView.Unit = item.MoneyUnit;
                    monthPlanDetailsView.TotalAmount = item.MoneyNum;
                    monthPlanDetailsView.YearPlanAmount = item.YearPlanMoneyNum;
                    monthPlanDetailsView.CurrentMonthPlanAmount = item.CurrentMonthPlanMoneyNum;

                    monthPlanDetailsView.CurrentMonthActualCompletedAmount = item.CurrentMonthActualCompletedMoneyNum;
                    if (!string.IsNullOrEmpty(item.CurrentMonthActualCompletedMoneyNum))
                    {
                        if (!string.IsNullOrEmpty(item.MoneyNum))
                        {
                            monthPlanDetailsView.CurrentMonthActualCompletedTotalProportion = Math.Round(Convert.ToDecimal(item.CurrentMonthActualCompletedMoneyNum) * 100 / Convert.ToDecimal(item.MoneyNum), 1).ToString() + "%";
                        }
                        if (!string.IsNullOrEmpty(item.YearPlanMoneyNum))
                        {
                            monthPlanDetailsView.CurrentMonthActualCompletedYearProportion = Math.Round(Convert.ToDecimal(item.CurrentMonthActualCompletedMoneyNum) * 100 / Convert.ToDecimal(item.YearPlanMoneyNum), 1).ToString() + "%";
                        }
                        if (!string.IsNullOrEmpty(item.CurrentMonthPlanMoneyNum))
                        {
                            monthPlanDetailsView.CurrentMonthActualCompletedMonthProportion = Math.Round(Convert.ToDecimal(item.CurrentMonthActualCompletedMoneyNum) * 100 / Convert.ToDecimal(item.CurrentMonthPlanMoneyNum), 1).ToString() + "%";
                        }
                    }

                    monthPlanDetailsView.CurrentYearCumulativeCompletedAmount = item.CurrentYearCumulativeCompletedMoneyNum;
                    if (!string.IsNullOrEmpty(item.CurrentYearCumulativeCompletedMoneyNum))
                    {
                        if (!string.IsNullOrEmpty(item.MoneyNum))
                        {
                            monthPlanDetailsView.CurrentYearCumulativeCompletedTotalProportion = Math.Round(Convert.ToDecimal(item.CurrentYearCumulativeCompletedMoneyNum) * 100 / Convert.ToDecimal(item.MoneyNum), 1).ToString() + "%";
                        }
                        if (!string.IsNullOrEmpty(item.YearPlanMoneyNum))
                        {
                            monthPlanDetailsView.CurrentYearCumulativeCompletedYearProportion = Math.Round(Convert.ToDecimal(item.CurrentYearCumulativeCompletedMoneyNum) * 100 / Convert.ToDecimal(item.YearPlanMoneyNum), 1).ToString() + "%";
                        }
                    }

                    monthPlanDetailsView.ConstructionCompletedAmount = item.ConstructionCompletedMoneyNum;
                    if (!string.IsNullOrEmpty(item.ConstructionCompletedMoneyNum))
                    {
                        if (!string.IsNullOrEmpty(item.MoneyNum))
                        {
                            monthPlanDetailsView.ConstructionCompletedTotalProportion = Math.Round(Convert.ToDecimal(item.ConstructionCompletedMoneyNum) * 100 / Convert.ToDecimal(item.MoneyNum), 1).ToString() + "%";
                        }
                    }

                    monthPlanDetailsView.NextMonthPlanAmount = item.NextMonthPlanMoneyNum;
                    if (!string.IsNullOrEmpty(item.NextMonthPlanMoneyNum))
                    {
                        if (!string.IsNullOrEmpty(item.YearPlanMoneyNum))
                        {
                            monthPlanDetailsView.NextMonthPlanYearProportion = Math.Round(Convert.ToDecimal(item.NextMonthPlanMoneyNum) * 100 / Convert.ToDecimal(item.YearPlanMoneyNum), 1).ToString() + "%";
                        }
                    }

                    lstMonthPlanDetailsView.Add(monthPlanDetailsView);
                }
            }
            return lstMonthPlanDetailsView;
        }

        public List<MonthPlanView> GetMonthPlanListForPreview(Guid projectID, string contractType, List<Guid> lstContractID)
        {
            #region 获取总金额
            decimal totalMoney = 0;
            foreach (Guid contractID in lstContractID)
            {
                string totalMoneyStr = GetTotalReviseMoney(projectID, contractType, contractID);
                if (!string.IsNullOrEmpty(totalMoneyStr))
                {
                    totalMoney += Convert.ToDecimal(totalMoneyStr);
                }
            }
            #endregion

            //获取所有的月度计划数据
            var lstMonthPlan = from mp in MonthPlanRepository.Entities
                               where mp.ProjectID == projectID && mp.ContractType == contractType && lstContractID.Contains(mp.ContractID)
                               select mp;

            //获取月度计划里面所有的年份
            List<MonthPlan> lstMonthPlanYear = lstMonthPlan.DistinctBy(mp => mp.Year).ToList();

            #region 获取所有年下面所选标段的年度计划修订数据,汇总所有年下每年的所选标段的年度修订金额
            Dictionary<string, Dictionary<Guid, YearPlanRevise>> lstYearPlanReviseForYear = new Dictionary<string, Dictionary<Guid, YearPlanRevise>>();
            Dictionary<string, decimal> lstTotalYearPlanReviseMonthForYear = new Dictionary<string, decimal>();
            foreach (MonthPlan monthPlan in lstMonthPlanYear)
            {
                Dictionary<Guid, YearPlanRevise> lstYearPlanReviseForContractID = new Dictionary<Guid, YearPlanRevise>();
                decimal yearPlanReviseMoney = 0;
                foreach (Guid contractID in lstContractID)
                {
                    YearPlanRevise yearPlanRevise = YearPlanReviseRepository.Entities.Where(yr => yr.ProjectID == projectID && yr.ContractType == contractType && yr.ContractID == contractID && yr.StatisticalCycle == monthPlan.Year).OrderByDescending(yr => yr.ReviseDate).FirstOrDefault();
                    if (yearPlanRevise != null)
                    {
                        if (!string.IsNullOrEmpty(yearPlanRevise.ReviseMoney as string))
                        {
                            yearPlanReviseMoney += Convert.ToDecimal(yearPlanRevise.ReviseMoney);
                        }
                        lstYearPlanReviseForContractID.Add(contractID, yearPlanRevise);
                    }
                }
                lstYearPlanReviseForYear.Add(monthPlan.Year, lstYearPlanReviseForContractID);
                lstTotalYearPlanReviseMonthForYear.Add(monthPlan.Year, yearPlanReviseMoney);
            }
            #endregion

            #region 构造月度计划初步数据
            List<MonthPlanView> lstMonthPlanView = new List<MonthPlanView>();
            foreach (MonthPlan monthPlan in lstMonthPlan)
            {
                MonthPlanView monthPlanView = lstMonthPlanView.SingleOrDefault(mp => mp.Year == monthPlan.Year && mp.Month == monthPlan.Month);
                if (monthPlanView != null)
                {
                    //设置当月计划
                    string lastYear = string.Empty;
                    string lastMonth = string.Empty;
                    SetLastYearAndMonth(monthPlan.Year, monthPlan.Month, ref lastYear, ref lastMonth);
                    YearPlanRevise yearPlanRevise = null;
                    if (lstYearPlanReviseForYear.ContainsKey(monthPlan.Year) && lstYearPlanReviseForYear[monthPlan.Year].ContainsKey(monthPlan.ContractID))
                    {
                        yearPlanRevise = lstYearPlanReviseForYear[monthPlan.Year][monthPlan.ContractID];
                    }
                    string currentMonthPlanMoneyNum = GetLastMonthMoney(projectID, contractType, monthPlan.ContractID, lastYear, lastMonth, yearPlanRevise, monthPlan.Month);
                    if (currentMonthPlanMoneyNum != "0")
                    {
                        monthPlanView.CurrentMonthPlanMoneyNum = (Convert.ToDecimal(monthPlanView.CurrentMonthPlanMoneyNum) + Convert.ToDecimal(currentMonthPlanMoneyNum)).ToString();
                    }

                    //设置本月实际完成
                    if (monthPlan.HandleState == "2" && !string.IsNullOrEmpty(monthPlan.TotalCurrentMonthActualCompletedMoneyNum as string))
                    {
                        monthPlanView.CurrentMonthActualCompletedMoneyNum = (Convert.ToDecimal(monthPlanView.CurrentMonthActualCompletedMoneyNum) + Convert.ToDecimal(monthPlan.TotalCurrentMonthActualCompletedMoneyNum)).ToString();
                    }

                    //设置本年累计和开工累计
                    decimal currentYearCumulativeCompletedMoney = 0;
                    decimal constructionCompletedMoneyNum = 0;
                    GetCumulativeCompletedMoney(projectID, contractType, monthPlan.ContractID, monthPlan.Year, monthPlan.Month, ref currentYearCumulativeCompletedMoney, ref constructionCompletedMoneyNum);
                    monthPlanView.CurrentYearCumulativeCompletedMoneyNum = (Convert.ToDecimal(monthPlanView.CurrentYearCumulativeCompletedMoneyNum) + currentYearCumulativeCompletedMoney).ToString();
                    monthPlanView.ConstructionCompletedMoneyNum = (Convert.ToDecimal(monthPlanView.ConstructionCompletedMoneyNum) + constructionCompletedMoneyNum).ToString();

                    //设置下月计划完成
                    if (monthPlan.HandleState == "2" && !string.IsNullOrEmpty(monthPlan.TotalNextMonthPlanMoneyNum as string))
                    {
                        monthPlanView.NextMonthPlanMoneyNum = (Convert.ToDecimal(monthPlanView.NextMonthPlanMoneyNum) + Convert.ToDecimal(monthPlan.TotalNextMonthPlanMoneyNum)).ToString();
                    }
                }
                else
                {
                    monthPlanView = new MonthPlanView();
                    monthPlanView.ID = GuidHelper.NewGuid();
                    monthPlanView.Year = monthPlan.Year;
                    monthPlanView.Month = monthPlan.Month;
                    monthPlanView.StatisticalCycle = monthPlan.Year + "年" + monthPlan.Month + "月";
                    monthPlanView.Unit = monthPlan.Unit;
                    monthPlanView.TotalMoneyNum = totalMoney == 0 ? string.Empty : totalMoney.ToString();

                    //设置年度计划修订金额
                    string yearPlanReviseMoney = string.Empty;
                    if (lstTotalYearPlanReviseMonthForYear.ContainsKey(monthPlan.Year) && lstTotalYearPlanReviseMonthForYear[monthPlan.Year] != 0)
                    {
                        yearPlanReviseMoney = lstTotalYearPlanReviseMonthForYear[monthPlan.Year].ToString();
                    }
                    monthPlanView.YearPlanMoneyNum = yearPlanReviseMoney;

                    //设置当月计划
                    string lastYear = string.Empty;
                    string lastMonth = string.Empty;
                    SetLastYearAndMonth(monthPlan.Year, monthPlan.Month, ref lastYear, ref lastMonth);
                    YearPlanRevise yearPlanRevise = null;
                    if (lstYearPlanReviseForYear.ContainsKey(monthPlan.Year) && lstYearPlanReviseForYear[monthPlan.Year].ContainsKey(monthPlan.ContractID))
                    {
                        yearPlanRevise = lstYearPlanReviseForYear[monthPlan.Year][monthPlan.ContractID];
                    }
                    monthPlanView.CurrentMonthPlanMoneyNum = GetLastMonthMoney(projectID, contractType, monthPlan.ContractID, lastYear, lastMonth, yearPlanRevise, monthPlan.Month);

                    //设置本月实际完成
                    monthPlanView.CurrentMonthActualCompletedMoneyNum = "0";
                    if (monthPlan.HandleState == "2" && !string.IsNullOrEmpty(monthPlan.TotalCurrentMonthActualCompletedMoneyNum as string))
                    {
                        monthPlanView.CurrentMonthActualCompletedMoneyNum = monthPlan.TotalCurrentMonthActualCompletedMoneyNum;
                    }

                    //设置本年累计和开工累计
                    decimal currentYearCumulativeCompletedMoney = 0;
                    decimal constructionCompletedMoneyNum = 0;
                    GetCumulativeCompletedMoney(projectID, contractType, monthPlan.ContractID, monthPlan.Year, monthPlan.Month, ref currentYearCumulativeCompletedMoney, ref constructionCompletedMoneyNum);
                    monthPlanView.CurrentYearCumulativeCompletedMoneyNum = currentYearCumulativeCompletedMoney.ToString();
                    monthPlanView.ConstructionCompletedMoneyNum = constructionCompletedMoneyNum.ToString();

                    //设置下月计划完成
                    monthPlanView.NextMonthPlanMoneyNum = "0";
                    if (monthPlan.HandleState == "2" && !string.IsNullOrEmpty(monthPlan.TotalNextMonthPlanMoneyNum as string))
                    {
                        monthPlanView.NextMonthPlanMoneyNum = monthPlan.TotalNextMonthPlanMoneyNum;
                    }
                    lstMonthPlanView.Add(monthPlanView);
                }
            }
            #endregion

            //设置最后返回数据
            foreach (MonthPlanView monthPlanView in lstMonthPlanView)
            {
                monthPlanView.CurrentMonthPlanMoneyNum = monthPlanView.CurrentMonthPlanMoneyNum == "0" ? string.Empty : monthPlanView.CurrentMonthPlanMoneyNum;
                monthPlanView.CurrentMonthActualCompletedMoneyNum = monthPlanView.CurrentMonthActualCompletedMoneyNum == "0" ? string.Empty : monthPlanView.CurrentMonthActualCompletedMoneyNum;
                if (!string.IsNullOrEmpty(monthPlanView.CurrentMonthActualCompletedMoneyNum))
                {
                    if (!string.IsNullOrEmpty(monthPlanView.TotalMoneyNum))
                    {
                        monthPlanView.CurrentMonthActualCompletedTotalProportion = Math.Round(Convert.ToDecimal(monthPlanView.CurrentMonthActualCompletedMoneyNum) * 100 / totalMoney, 1).ToString() + "%";
                    }
                    if (!string.IsNullOrEmpty(monthPlanView.YearPlanMoneyNum))
                    {
                        monthPlanView.CurrentMonthActualCompletedYearProportion = Math.Round(Convert.ToDecimal(monthPlanView.CurrentMonthActualCompletedMoneyNum) * 100 / Convert.ToDecimal(monthPlanView.YearPlanMoneyNum), 1).ToString() + "%";
                    }
                    if (!string.IsNullOrEmpty(monthPlanView.CurrentMonthPlanMoneyNum))
                    {
                        monthPlanView.CurrentMonthActualCompletedMonthProportion = Math.Round(Convert.ToDecimal(monthPlanView.CurrentMonthActualCompletedMoneyNum) * 100 / Convert.ToDecimal(monthPlanView.CurrentMonthPlanMoneyNum), 1).ToString() + "%";
                    }
                }

                monthPlanView.CurrentYearCumulativeCompletedMoneyNum = monthPlanView.CurrentYearCumulativeCompletedMoneyNum == "0" ? string.Empty : monthPlanView.CurrentYearCumulativeCompletedMoneyNum;
                if (!string.IsNullOrEmpty(monthPlanView.CurrentYearCumulativeCompletedMoneyNum))
                {
                    if (!string.IsNullOrEmpty(monthPlanView.TotalMoneyNum))
                    {
                        monthPlanView.CurrentYearCumulativeCompletedTotalProportion = Math.Round(Convert.ToDecimal(monthPlanView.CurrentYearCumulativeCompletedMoneyNum) * 100 / totalMoney, 1).ToString() + "%";
                    }
                    if (!string.IsNullOrEmpty(monthPlanView.YearPlanMoneyNum))
                    {
                        monthPlanView.CurrentYearCumulativeCompletedYearProportion = Math.Round(Convert.ToDecimal(monthPlanView.CurrentYearCumulativeCompletedMoneyNum) * 100 / Convert.ToDecimal(monthPlanView.YearPlanMoneyNum), 1).ToString() + "%";
                    }
                }

                monthPlanView.ConstructionCompletedMoneyNum = monthPlanView.ConstructionCompletedMoneyNum == "0" ? string.Empty : monthPlanView.ConstructionCompletedMoneyNum;
                if (!string.IsNullOrEmpty(monthPlanView.ConstructionCompletedMoneyNum))
                {
                    if (!string.IsNullOrEmpty(monthPlanView.TotalMoneyNum))
                    {
                        monthPlanView.ConstructionCompletedTotalProportion = Math.Round(Convert.ToDecimal(monthPlanView.ConstructionCompletedMoneyNum) * 100 / totalMoney, 1).ToString() + "%";
                    }
                }

                monthPlanView.NextMonthPlanMoneyNum = monthPlanView.NextMonthPlanMoneyNum == "0" ? string.Empty : monthPlanView.NextMonthPlanMoneyNum;
                if (!string.IsNullOrEmpty(monthPlanView.NextMonthPlanMoneyNum))
                {

                    if (!string.IsNullOrEmpty(monthPlanView.YearPlanMoneyNum))
                    {
                        monthPlanView.NextMonthPlanYearProportion = Math.Round(Convert.ToDecimal(monthPlanView.NextMonthPlanMoneyNum) * 100 / Convert.ToDecimal(monthPlanView.YearPlanMoneyNum), 1).ToString() + "%";
                    }
                }
            }

            return lstMonthPlanView.OrderByDescending(mp => mp.Year).ThenByDescending(mp => mp.Month).ToList();
        }

        public List<MonthPlanDetailsView> GetMonthPlanDetailListForPreview(Guid projectID, string contractType, List<Guid> lstContractID, string year, string month)
        {
            #region 获取各个子查询数据
            List<TempModel> lstTotalReviseDetail = new List<TempModel>();
            List<TempModel> lstYearPlanReviseDetail = new List<TempModel>();
            List<TempModel> lstLastMonthDetail = new List<TempModel>();
            List<MonthPlanDetails> lstMonthPlanDetail = new List<MonthPlanDetails>();
            List<TempModel> lstCurrentYearCumulativeCompleted = new List<TempModel>();
            List<TempModel> lstConstructionCompleted = new List<TempModel>();
            foreach (Guid contractID in lstContractID)
            {
                //获取总量维护修订明细
                TotalRevise totalRevise = TotalReviseRepository.Entities.Where(t => t.ProjectID == projectID && t.ContractType == contractType && t.ContractID == contractID).OrderByDescending(t => t.ReviseDate).FirstOrDefault();
                if (totalRevise != null)
                {
                    List<TotalReviseDetails> lstTotalReviseDetailForOneContractID = TotalReviseDetailsRepository.Entities.Where(td => td.TotalReviseID == totalRevise.ID).ToList();
                    TotalTempModelForTotalReviseDetail(lstTotalReviseDetailForOneContractID, lstTotalReviseDetail);
                }

                //获取年度计划修订明细
                YearPlanRevise yearPlanRevise = YearPlanReviseRepository.Entities.Where(yr => yr.ProjectID == projectID && yr.ContractType == contractType && yr.ContractID == contractID && yr.StatisticalCycle == year).OrderByDescending(yr => yr.ReviseDate).FirstOrDefault();
                if (yearPlanRevise != null)
                {
                    List<YearPlanReviseDetails> lstYearPlanReviseDetailForOneContractID = YearPlanReviseDetailsRepository.Entities.Where(yrd => yrd.YearPlanReviseID == yearPlanRevise.ID).ToList();
                    TotalTempModelForYearPlanReviseDetail(lstYearPlanReviseDetailForOneContractID, lstYearPlanReviseDetail);
                }

                //设置当前年月的上一个月
                string lastYear = string.Empty;
                string lastMonth = string.Empty;
                SetLastYearAndMonth(year, month, ref lastYear, ref lastMonth);

                //获取上月计划明细
                List<TempModel> lstLastMonthDetailForOneContractID = GetLastMonthDetails(projectID, contractType, contractID, lastYear, lastMonth, yearPlanRevise, month);
                TotalTempModel(lstLastMonthDetailForOneContractID, lstLastMonthDetail);

                //获取月度计划明细
                IQueryable<MonthPlanDetails> lstMonthPlanDetailForOneContractID = from m in MonthPlanRepository.Entities
                                                                                  join md in MonthPlanDetailsRepository.Entities
                                                                                  on m.ID equals md.MonthPlanID
                                                                                  where m.ProjectID == projectID && m.ContractType == contractType && m.ContractID == contractID && m.Year == year && m.Month == month && m.HandleState == "2"
                                                                                  select md;
                TotalTempModelForMonthPlanDetail(lstMonthPlanDetailForOneContractID, lstMonthPlanDetail);

                //获取本年累计和开工累计
                List<TempModel> lstCurrentYearCumulativeCompletedForOneContractID = new List<TempModel>();
                List<TempModel> lstConstructionCompletedForOneContractID = new List<TempModel>();
                GetCumulativeCompletedDetails(projectID, contractType, contractID, year, month, lstCurrentYearCumulativeCompletedForOneContractID, lstConstructionCompletedForOneContractID);
                TotalTempModel(lstCurrentYearCumulativeCompletedForOneContractID, lstCurrentYearCumulativeCompleted);
                TotalTempModel(lstConstructionCompletedForOneContractID, lstConstructionCompleted);
            }
            #endregion

            //获取连接查询数据
            var queryData = from s in StatisticsItemMaintenanceRepository.Entities.ToList()
                            join td in lstTotalReviseDetail
                            on s.ID equals td.StatisticsItemID into joinedEmpTD
                            from tempTD in joinedEmpTD.DefaultIfEmpty()

                            join yd in lstYearPlanReviseDetail
                            on s.ID equals yd.StatisticsItemID into joinedEmpYD
                            from tempYD in joinedEmpYD.DefaultIfEmpty()

                            join lmd in lstLastMonthDetail
                            on s.ID equals lmd.StatisticsItemID into joinedEmpLMD
                            from tempLMD in joinedEmpLMD.DefaultIfEmpty()

                            join md in lstMonthPlanDetail
                            on s.ID equals md.StatisticsItemID into joinedEmpMD
                            from tempMD in joinedEmpMD.DefaultIfEmpty()

                            join crc in lstCurrentYearCumulativeCompleted
                            on s.ID equals crc.StatisticsItemID into joinedEmpCRC
                            from tempCRC in joinedEmpCRC.DefaultIfEmpty()

                            join cc in lstConstructionCompleted
                            on s.ID equals cc.StatisticsItemID into joinedEmpCC
                            from tempCC in joinedEmpCC.DefaultIfEmpty()

                            where s.IsParent == false && s.ProjectID == projectID && s.ContractType == contractType
                            orderby s.OrderNo
                            select new
                            {
                                StatisticsItemID = s.ID,
                                s.StatisticsItemName,
                                s.PID,
                                s.EngineeringUnit,
                                s.MoneyUnit,
                                EngineeringNum = tempTD == null ? string.Empty : tempTD.EngineeringNum,
                                MoneyNum = tempTD == null ? string.Empty : tempTD.MoneyNum,
                                YearPlanEngineeringNum = tempYD == null ? string.Empty : tempYD.EngineeringNum,
                                YearPlanMoneyNum = tempYD == null ? string.Empty : tempYD.MoneyNum,
                                CurrentMonthPlanEngineeringNum = tempLMD == null ? string.Empty : tempLMD.EngineeringNum,
                                CurrentMonthPlanMoneyNum = tempLMD == null ? string.Empty : tempLMD.MoneyNum,
                                ID = tempMD == null ? GuidHelper.NewGuid() : tempMD.ID,
                                CurrentMonthActualCompletedEngineeringNum = tempMD == null ? string.Empty : tempMD.CurrentMonthActualCompletedEngineeringNum,
                                CurrentMonthActualCompletedMoneyNum = tempMD == null ? string.Empty : tempMD.CurrentMonthActualCompletedMoneyNum,
                                NextMonthPlanEngineeringNum = tempMD == null ? string.Empty : tempMD.NextMonthPlanEngineeringNum,
                                NextMonthPlanMoneyNum = tempMD == null ? string.Empty : tempMD.NextMonthPlanMoneyNum,
                                CurrentYearCumulativeCompletedEngineeringNum = tempCRC == null ? string.Empty : tempCRC.EngineeringNum,
                                CurrentYearCumulativeCompletedMoneyNum = tempCRC == null ? string.Empty : tempCRC.MoneyNum,
                                ConstructionCompletedEngineeringNum = tempCC == null ? string.Empty : tempCC.EngineeringNum,
                                ConstructionCompletedMoneyNum = tempCC == null ? string.Empty : tempCC.MoneyNum
                            };

            List<MonthPlanDetailsView> lstMonthPlanDetailsView = new List<MonthPlanDetailsView>();
            foreach (var item in queryData)
            {
                string parentStatisticsItemName = item.StatisticsItemName;
                if (item.PID != null)
                {
                    parentStatisticsItemName = GetParentStatisticsItemName(item.PID);
                }

                if (!string.IsNullOrEmpty(item.EngineeringUnit))
                {
                    MonthPlanDetailsView monthPlanDetailsView = new MonthPlanDetailsView();
                    monthPlanDetailsView.ID = item.ID;
                    monthPlanDetailsView.StatisticsItemID = item.StatisticsItemID;
                    monthPlanDetailsView.StatisticsItemName = item.StatisticsItemName;
                    monthPlanDetailsView.ParentStatisticsItemName = parentStatisticsItemName;
                    monthPlanDetailsView.Unit = item.EngineeringUnit;
                    monthPlanDetailsView.TotalAmount = item.EngineeringNum;
                    monthPlanDetailsView.YearPlanAmount = item.YearPlanEngineeringNum;
                    monthPlanDetailsView.CurrentMonthPlanAmount = item.CurrentMonthPlanEngineeringNum;

                    monthPlanDetailsView.CurrentMonthActualCompletedAmount = item.CurrentMonthActualCompletedEngineeringNum;
                    if (!string.IsNullOrEmpty(item.CurrentMonthActualCompletedEngineeringNum))
                    {
                        monthPlanDetailsView.CurrentMonthActualCompletedTotalProportion = CountProportion(item.CurrentMonthActualCompletedEngineeringNum, item.EngineeringNum);
                        monthPlanDetailsView.CurrentMonthActualCompletedYearProportion = CountProportion(item.CurrentMonthActualCompletedEngineeringNum, item.YearPlanEngineeringNum);
                        monthPlanDetailsView.CurrentMonthActualCompletedMonthProportion = CountProportion(item.CurrentMonthActualCompletedEngineeringNum, item.CurrentMonthPlanEngineeringNum);
                    }

                    monthPlanDetailsView.CurrentYearCumulativeCompletedAmount = item.CurrentYearCumulativeCompletedEngineeringNum;
                    if (!string.IsNullOrEmpty(item.CurrentYearCumulativeCompletedEngineeringNum))
                    {
                        monthPlanDetailsView.CurrentYearCumulativeCompletedTotalProportion = CountProportion(item.CurrentYearCumulativeCompletedEngineeringNum, item.EngineeringNum);
                        monthPlanDetailsView.CurrentYearCumulativeCompletedYearProportion = CountProportion(item.CurrentYearCumulativeCompletedEngineeringNum, item.YearPlanEngineeringNum);
                    }

                    monthPlanDetailsView.ConstructionCompletedAmount = item.ConstructionCompletedEngineeringNum;
                    if (!string.IsNullOrEmpty(item.ConstructionCompletedEngineeringNum))
                    {
                        monthPlanDetailsView.ConstructionCompletedTotalProportion = CountProportion(item.ConstructionCompletedEngineeringNum, item.EngineeringNum);
                    }

                    monthPlanDetailsView.NextMonthPlanAmount = item.NextMonthPlanEngineeringNum;
                    if (!string.IsNullOrEmpty(item.NextMonthPlanEngineeringNum))
                    {
                        monthPlanDetailsView.NextMonthPlanYearProportion = CountProportion(item.NextMonthPlanEngineeringNum, item.YearPlanEngineeringNum);
                    }

                    lstMonthPlanDetailsView.Add(monthPlanDetailsView);
                }

                if (!string.IsNullOrEmpty(item.MoneyUnit))
                {
                    MonthPlanDetailsView monthPlanDetailsView = new MonthPlanDetailsView();
                    monthPlanDetailsView.ID = item.ID;
                    monthPlanDetailsView.StatisticsItemID = item.StatisticsItemID;
                    monthPlanDetailsView.StatisticsItemName = item.StatisticsItemName;
                    monthPlanDetailsView.ParentStatisticsItemName = parentStatisticsItemName;
                    monthPlanDetailsView.Unit = item.MoneyUnit;
                    monthPlanDetailsView.TotalAmount = item.MoneyNum;
                    monthPlanDetailsView.YearPlanAmount = item.YearPlanMoneyNum;
                    monthPlanDetailsView.CurrentMonthPlanAmount = item.CurrentMonthPlanMoneyNum;

                    monthPlanDetailsView.CurrentMonthActualCompletedAmount = item.CurrentMonthActualCompletedMoneyNum;
                    if (!string.IsNullOrEmpty(item.CurrentMonthActualCompletedMoneyNum))
                    {
                        if (!string.IsNullOrEmpty(item.MoneyNum))
                        {
                            monthPlanDetailsView.CurrentMonthActualCompletedTotalProportion = Math.Round(Convert.ToDecimal(item.CurrentMonthActualCompletedMoneyNum) * 100 / Convert.ToDecimal(item.MoneyNum), 1).ToString() + "%";
                        }
                        if (!string.IsNullOrEmpty(item.YearPlanMoneyNum))
                        {
                            monthPlanDetailsView.CurrentMonthActualCompletedYearProportion = Math.Round(Convert.ToDecimal(item.CurrentMonthActualCompletedMoneyNum) * 100 / Convert.ToDecimal(item.YearPlanMoneyNum), 1).ToString() + "%";
                        }
                        if (!string.IsNullOrEmpty(item.CurrentMonthPlanMoneyNum))
                        {
                            monthPlanDetailsView.CurrentMonthActualCompletedMonthProportion = Math.Round(Convert.ToDecimal(item.CurrentMonthActualCompletedMoneyNum) * 100 / Convert.ToDecimal(item.CurrentMonthPlanMoneyNum), 1).ToString() + "%";
                        }
                    }

                    monthPlanDetailsView.CurrentYearCumulativeCompletedAmount = item.CurrentYearCumulativeCompletedMoneyNum;
                    if (!string.IsNullOrEmpty(item.CurrentYearCumulativeCompletedMoneyNum))
                    {
                        if (!string.IsNullOrEmpty(item.MoneyNum))
                        {
                            monthPlanDetailsView.CurrentYearCumulativeCompletedTotalProportion = Math.Round(Convert.ToDecimal(item.CurrentYearCumulativeCompletedMoneyNum) * 100 / Convert.ToDecimal(item.MoneyNum), 1).ToString() + "%";
                        }
                        if (!string.IsNullOrEmpty(item.YearPlanMoneyNum))
                        {
                            monthPlanDetailsView.CurrentYearCumulativeCompletedYearProportion = Math.Round(Convert.ToDecimal(item.CurrentYearCumulativeCompletedMoneyNum) * 100 / Convert.ToDecimal(item.YearPlanMoneyNum), 1).ToString() + "%";
                        }
                    }

                    monthPlanDetailsView.ConstructionCompletedAmount = item.ConstructionCompletedMoneyNum;
                    if (!string.IsNullOrEmpty(item.ConstructionCompletedMoneyNum))
                    {
                        if (!string.IsNullOrEmpty(item.MoneyNum))
                        {
                            monthPlanDetailsView.ConstructionCompletedTotalProportion = Math.Round(Convert.ToDecimal(item.ConstructionCompletedMoneyNum) * 100 / Convert.ToDecimal(item.MoneyNum), 1).ToString() + "%";
                        }
                    }

                    monthPlanDetailsView.NextMonthPlanAmount = item.NextMonthPlanMoneyNum;
                    if (!string.IsNullOrEmpty(item.NextMonthPlanMoneyNum))
                    {
                        if (!string.IsNullOrEmpty(item.YearPlanMoneyNum))
                        {
                            monthPlanDetailsView.NextMonthPlanYearProportion = Math.Round(Convert.ToDecimal(item.NextMonthPlanMoneyNum) * 100 / Convert.ToDecimal(item.YearPlanMoneyNum), 1).ToString() + "%";
                        }
                    }

                    lstMonthPlanDetailsView.Add(monthPlanDetailsView);
                }
            }
            return lstMonthPlanDetailsView;
        }
        #endregion

        #region 单据加载
        public MonthPlanView GetMonthPlanByID(Guid id)
        {
            MonthPlan monthPlan = MonthPlanRepository.Entities.SingleOrDefault(t => t.ID == id);
            MonthPlanView monthPlanView = null;
            if (monthPlan != null)
            {
                monthPlanView = new MonthPlanView();
                monthPlanView.ID = monthPlan.ID;
                monthPlanView.FlowCode = monthPlan.FlowCode;
                monthPlanView.ProjectID = monthPlan.ProjectID;
                monthPlanView.ContractType = monthPlan.ContractType;
                monthPlanView.ContractID = monthPlan.ContractID;
                monthPlanView.Year = monthPlan.Year;
                monthPlanView.Month = monthPlan.Month;
                monthPlanView.StatisticalCycle = monthPlan.Year + "年" + monthPlan.Month + "月";
                monthPlanView.Unit = monthPlan.Unit;
                monthPlanView.TotalCurrentMonthActualCompletedMoneyNum = monthPlan.TotalCurrentMonthActualCompletedMoneyNum;
                monthPlanView.TotalNextMonthPlanMoneyNum = monthPlan.TotalNextMonthPlanMoneyNum;
                monthPlanView.RequestDate = monthPlan.RequestDate;
                monthPlanView.RequestPerson = monthPlan.RequestPerson;
                monthPlanView.HandleState = monthPlan.HandleState;
                monthPlanView.AssociatedNodeCode = monthPlan.AssociatedNodeCode;
                monthPlanView.LastUpdateUserDepartment = monthPlan.LastUpdateUserDepartment;
                monthPlanView.LastUpdateUser = monthPlan.LastUpdateUser;
                monthPlanView.LastUpdateTime = monthPlan.LastUpdateTime;
                monthPlanView.SaveState = monthPlan.SaveState;
            }
            return monthPlanView;
        }

        public List<MonthPlanDetailsView> GetMonthPlanDetailListForFlow(Guid projectID, string contractType, Guid contractID, string year, string month, Guid monthPlanID)
        {
            //获取总量维护修订ID
            Guid reviseID = GuidHelper.NewGuid();
            TotalRevise totalRevise = TotalReviseRepository.Entities.Where(t => t.ProjectID == projectID && t.ContractType == contractType && t.ContractID == contractID).OrderByDescending(t => t.ReviseDate).FirstOrDefault();
            if (totalRevise != null)
            {
                reviseID = totalRevise.ID;
            }

            //获取总量维护修订明细
            var queryTotalReviseDetails = from tr in TotalReviseDetailsRepository.Entities
                                          where tr.TotalReviseID == reviseID
                                          select tr;

            //获取年度计划修订ID
            Guid yearPlanReviseID = GuidHelper.NewGuid();
            YearPlanRevise yearPlanRevise = YearPlanReviseRepository.Entities.Where(yr => yr.ProjectID == projectID && yr.ContractType == contractType && yr.ContractID == contractID && yr.StatisticalCycle == year).OrderByDescending(yr => yr.ReviseDate).FirstOrDefault();
            if (yearPlanRevise != null)
            {
                yearPlanReviseID = yearPlanRevise.ID;
            }

            //获取年度计划修订明细
            var queryYearPlanReviseDetails = from yrd in YearPlanReviseDetailsRepository.Entities
                                             where yrd.YearPlanReviseID == yearPlanReviseID
                                             select yrd;

            //设置当前年月的上一个月
            string lastYear = string.Empty;
            string lastMonth = string.Empty;
            SetLastYearAndMonth(year, month, ref lastYear, ref lastMonth);


            //获取上月计划明细
            List<TempModel> lstLastMonthDetail = GetLastMonthDetails(projectID, contractType, contractID, lastYear, lastMonth, yearPlanRevise, month);


            //获取月度计划明细
            var queryMonthPlanDetails = from md in MonthPlanDetailsRepository.Entities
                                        where md.MonthPlanID == monthPlanID
                                        select md;

            var queryData = from s in StatisticsItemMaintenanceRepository.Entities.ToList()
                            join td in queryTotalReviseDetails
                            on s.ID equals td.StatisticsItemID into joinedEmpTD
                            from tempTD in joinedEmpTD.DefaultIfEmpty()

                            join yd in queryYearPlanReviseDetails
                            on s.ID equals yd.StatisticsItemID into joinedEmpYD
                            from tempYD in joinedEmpYD.DefaultIfEmpty()

                            join lmd in lstLastMonthDetail
                            on s.ID equals lmd.StatisticsItemID into joinedEmpLMD
                            from tempLMD in joinedEmpLMD.DefaultIfEmpty()

                            join md in queryMonthPlanDetails
                            on s.ID equals md.StatisticsItemID into joinedEmpMD
                            from tempMD in joinedEmpMD.DefaultIfEmpty()
                            where s.IsParent == false && s.ProjectID == projectID && s.ContractType == contractType
                            orderby s.OrderNo
                            select new
                            {
                                StatisticsItemID = s.ID,
                                s.StatisticsItemName,
                                s.PID,
                                s.EngineeringUnit,
                                s.MoneyUnit,
                                EngineeringNum = tempTD == null ? string.Empty : tempTD.EngineeringNum,
                                MoneyNum = tempTD == null ? string.Empty : tempTD.MoneyNum,
                                MonthPlanID = monthPlanID,
                                YearPlanEngineeringNum = tempYD == null ? string.Empty : tempYD.TotalEngineeringNum,
                                YearPlanMoneyNum = tempYD == null ? string.Empty : tempYD.TotalMoneyNum,
                                CurrentMonthPlanEngineeringNum = tempLMD == null ? string.Empty : tempLMD.EngineeringNum,
                                CurrentMonthPlanMoneyNum = tempLMD == null ? string.Empty : tempLMD.MoneyNum,
                                ID = tempMD == null ? GuidHelper.NewGuid() : tempMD.ID,
                                CurrentMonthActualCompletedEngineeringNum = tempMD == null ? string.Empty : tempMD.CurrentMonthActualCompletedEngineeringNum,
                                CurrentMonthActualCompletedMoneyNum = tempMD == null ? string.Empty : tempMD.CurrentMonthActualCompletedMoneyNum,
                                NextMonthPlanEngineeringNum = tempMD == null ? string.Empty : tempMD.NextMonthPlanEngineeringNum,
                                NextMonthPlanMoneyNum = tempMD == null ? string.Empty : tempMD.NextMonthPlanMoneyNum
                            };

            List<MonthPlanDetailsView> lstMonthPlanDetailsView = new List<MonthPlanDetailsView>();
            foreach (var item in queryData)
            {
                string parentStatisticsItemName = item.StatisticsItemName;
                if (item.PID != null)
                {
                    parentStatisticsItemName = GetParentStatisticsItemName(item.PID);
                }

                if (!string.IsNullOrEmpty(item.EngineeringUnit))
                {
                    MonthPlanDetailsView monthPlanDetailsView = new MonthPlanDetailsView();
                    monthPlanDetailsView.ID = item.ID;
                    monthPlanDetailsView.MonthPlanID = item.MonthPlanID;
                    monthPlanDetailsView.StatisticsItemID = item.StatisticsItemID;
                    monthPlanDetailsView.StatisticsItemName = item.StatisticsItemName;
                    monthPlanDetailsView.ParentStatisticsItemName = parentStatisticsItemName;
                    monthPlanDetailsView.Unit = item.EngineeringUnit;
                    monthPlanDetailsView.TotalAmount = item.EngineeringNum;
                    monthPlanDetailsView.YearPlanAmount = item.YearPlanEngineeringNum;
                    monthPlanDetailsView.CurrentMonthPlanAmount = item.CurrentMonthPlanEngineeringNum;
                    monthPlanDetailsView.CurrentMonthActualCompletedAmount = item.CurrentMonthActualCompletedEngineeringNum;
                    monthPlanDetailsView.NextMonthPlanAmount = item.NextMonthPlanEngineeringNum;
                    monthPlanDetailsView.IsBelongToMoneyNum = "0";
                    lstMonthPlanDetailsView.Add(monthPlanDetailsView);
                }

                if (!string.IsNullOrEmpty(item.MoneyUnit))
                {
                    MonthPlanDetailsView monthPlanDetailsView = new MonthPlanDetailsView();
                    monthPlanDetailsView.ID = item.ID;
                    monthPlanDetailsView.MonthPlanID = item.MonthPlanID;
                    monthPlanDetailsView.StatisticsItemID = item.StatisticsItemID;
                    monthPlanDetailsView.StatisticsItemName = item.StatisticsItemName;
                    monthPlanDetailsView.ParentStatisticsItemName = parentStatisticsItemName;
                    monthPlanDetailsView.Unit = item.MoneyUnit;
                    monthPlanDetailsView.TotalAmount = item.MoneyNum;
                    monthPlanDetailsView.YearPlanAmount = item.YearPlanMoneyNum;
                    monthPlanDetailsView.CurrentMonthPlanAmount = item.CurrentMonthPlanMoneyNum;
                    monthPlanDetailsView.CurrentMonthActualCompletedAmount = item.CurrentMonthActualCompletedMoneyNum;
                    monthPlanDetailsView.NextMonthPlanAmount = item.NextMonthPlanMoneyNum;
                    monthPlanDetailsView.IsBelongToMoneyNum = "1";
                    lstMonthPlanDetailsView.Add(monthPlanDetailsView);
                }
            }
            return lstMonthPlanDetailsView;
        }
        #endregion

        #region 单据保存
        public void SaveMonthPlan(MonthPlanView monthPlanView, List<MonthPlanDetailsView> saveList, bool isUpdateDetails = true)
        {
            MonthPlan record = MonthPlanRepository.Entities.FirstOrDefault(a => a.ID == monthPlanView.ID);
            if (record != null)
            {
                UpdateMonthPlan(record, monthPlanView);
            }
            else
            {
                InsertMonthPlan(monthPlanView);
            }

            if (isUpdateDetails)
            {
                DeleteMonthPlanDetails(monthPlanView.ID);
                foreach (MonthPlanDetailsView monthPlanDetailsView in saveList)
                {
                    InsertMonthPlanDetails(monthPlanDetailsView);
                }
            }
        }

        private void InsertMonthPlan(MonthPlanView monthPlanView)
        {
            MonthPlan record = new MonthPlan()
            {
                ID = monthPlanView.ID,
                FlowCode = monthPlanView.FlowCode,
                ProjectID = monthPlanView.ProjectID,
                ContractType = monthPlanView.ContractType,
                ContractID = monthPlanView.ContractID,
                Year = monthPlanView.Year,
                Month = monthPlanView.Month,
                Unit = monthPlanView.Unit,
                TotalCurrentMonthActualCompletedMoneyNum = monthPlanView.TotalCurrentMonthActualCompletedMoneyNum,
                TotalNextMonthPlanMoneyNum = monthPlanView.TotalNextMonthPlanMoneyNum,
                RequestDate = monthPlanView.RequestDate,
                RequestPerson = monthPlanView.RequestPerson,
                HandleState = monthPlanView.HandleState,
                AssociatedNodeCode = monthPlanView.AssociatedNodeCode,
                LastUpdateUserDepartment = monthPlanView.LastUpdateUserDepartment,
                LastUpdateUser = monthPlanView.LastUpdateUser,
                LastUpdateTime = monthPlanView.LastUpdateTime,
                SaveState = monthPlanView.SaveState
            };
            MonthPlanRepository.Insert(record);
        }

        private void UpdateMonthPlan(MonthPlan record, MonthPlanView monthPlanView)
        {
            record.Year = monthPlanView.Year;
            record.Month = monthPlanView.Month;
            record.Unit = monthPlanView.Unit;
            record.TotalCurrentMonthActualCompletedMoneyNum = monthPlanView.TotalCurrentMonthActualCompletedMoneyNum;
            record.TotalNextMonthPlanMoneyNum = monthPlanView.TotalNextMonthPlanMoneyNum;
            record.HandleState = monthPlanView.HandleState;
            record.AssociatedNodeCode = monthPlanView.AssociatedNodeCode;
            record.LastUpdateUserDepartment = monthPlanView.LastUpdateUserDepartment;
            record.LastUpdateUser = monthPlanView.LastUpdateUser;
            record.LastUpdateTime = monthPlanView.LastUpdateTime;
            record.SaveState = monthPlanView.SaveState;
            MonthPlanRepository.Update(record);
        }

        private void DeleteMonthPlanDetails(Guid monthPlanID)
        {
            List<MonthPlanDetails> lstMonthPlanDetails = MonthPlanDetailsRepository.Entities.Where(a => a.MonthPlanID == monthPlanID).ToList();
            foreach (MonthPlanDetails monthPlanDetails in lstMonthPlanDetails)
            {
                MonthPlanDetailsRepository.Delete(monthPlanDetails.ID);
            }
        }

        private void InsertMonthPlanDetails(MonthPlanDetailsView monthPlanDetailsView)
        {
            MonthPlanDetails record = new MonthPlanDetails()
            {
                ID = monthPlanDetailsView.ID,
                MonthPlanID = monthPlanDetailsView.MonthPlanID,
                StatisticsItemID = monthPlanDetailsView.StatisticsItemID,
                CurrentMonthActualCompletedEngineeringNum = monthPlanDetailsView.CurrentMonthActualCompletedEngineeringNum,
                CurrentMonthActualCompletedMoneyNum = monthPlanDetailsView.CurrentMonthActualCompletedMoneyNum,
                NextMonthPlanEngineeringNum = monthPlanDetailsView.NextMonthPlanEngineeringNum,
                NextMonthPlanMoneyNum = monthPlanDetailsView.NextMonthPlanMoneyNum
            };
            MonthPlanDetailsRepository.Insert(record);
        }
        #endregion

        public OperationResult Delete(Guid id)
        {
            try
            {
                MonthPlan record = MonthPlanRepository.Entities.SingleOrDefault(t => t.ID == id);
                if (record == null)
                    return new OperationResult(OperationResultType.QueryNull, "未找到指定的记录");
                if (record != null)
                {
                    MonthPlanRepository.Delete(record);
                }

                string sql = @"DELETE FROM MonthPlanDetails WHERE MonthPlanID='" + record.ID + "';" +
                              "DELETE FROM BaklogTasks WHERE RecordID='" + record.ID + "';" +
                              "DELETE FROM BaklogTaskTemps WHERE RecordID='" + record.ID + "';" +
                              "DELETE FROM CompleteFlowNodes WHERE RecordID='" + record.ID + "';" +
                              "DELETE FROM FlowGraphNodes WHERE RecordID='" + record.ID + "';" +
                              "DELETE FROM FlowProcessMessages WHERE RecordID='" + record.ID + "';" +
                              "DELETE FROM ProcessedTasks WHERE RecordID='" + record.ID + "';";
                MonthPlanRepository.ExeSqlCommon(sql);
                return new OperationResult(OperationResultType.Success, "删除成功", record);
            }
            catch (Exception ex)
            {
                return new OperationResult(OperationResultType.Error, "删除失败:" + ex.Message);
            }
        }

        #region 统计分析
        public List<StatisticalAnalysisView> GetStatisticalAnalysisList(Guid projectID, string contractType, string year, List<string> lstMonth, List<Guid> lstContractID)
        {
            List<StatisticalAnalysisView> lstStatisticalAnalysisView = new List<StatisticalAnalysisView>();
            foreach (Guid contractID in lstContractID)
            {
                StatisticalAnalysisView statisticalAnalysisView = new StatisticalAnalysisView();
                statisticalAnalysisView.ContractID = contractID;

                string sql = "select * from V_ContractInfoes where ID='" + contractID + "'";
                var lstContractInfoView = DbSqlHelper<VMContractInfo>.SqlQueryCommon(sql);
                if (lstContractInfoView.Count == 1)
                {
                    statisticalAnalysisView.ContractName = lstContractInfoView[0].ContractName;
                }

                statisticalAnalysisView.Unit = "万元";
                string totalMoney = GetTotalReviseMoney(projectID, contractType, contractID);
                statisticalAnalysisView.TotalMoneyNum = totalMoney;

                YearPlanRevise yearPlanRevise = YearPlanReviseRepository.Entities.Where(yr => yr.ProjectID == projectID && yr.ContractType == contractType && yr.ContractID == contractID && yr.StatisticalCycle == year).OrderByDescending(yr => yr.ReviseDate).FirstOrDefault();
                if (yearPlanRevise != null)
                {
                    statisticalAnalysisView.YearPlanMoneyNum = yearPlanRevise.ReviseMoney == "0" ? string.Empty : yearPlanRevise.ReviseMoney;
                }

                decimal currentMonthPlanMoneyNum = 0;
                decimal currentMonthActualCompletedMoneyNum = 0;
                foreach (string month in lstMonth)
                {
                    //string lastYear = string.Empty;
                    //string lastMonth = string.Empty;
                    //SetLastYearAndMonth(year, month, ref lastYear, ref lastMonth);
                    //currentMonthPlanMoneyNum += Convert.ToDecimal(GetLastMonthMoney(projectID, contractType, contractID, lastYear, lastMonth, yearPlanRevise, month));
                    currentMonthPlanMoneyNum += Convert.ToDecimal(GetMonthMoneyFromYearPlanRevise(yearPlanRevise, month));

                    MonthPlan monthPlan = MonthPlanRepository.Entities.SingleOrDefault(mp => mp.ProjectID == projectID && mp.ContractType == contractType && mp.ContractID == contractID && mp.Year == year && mp.Month == month);
                    if (monthPlan != null && monthPlan.HandleState == "2" && !string.IsNullOrEmpty(monthPlan.TotalCurrentMonthActualCompletedMoneyNum as string))
                    {
                        currentMonthActualCompletedMoneyNum += Convert.ToDecimal(monthPlan.TotalCurrentMonthActualCompletedMoneyNum);
                    }
                }

                statisticalAnalysisView.CurrentMonthPlanMoneyNum = currentMonthPlanMoneyNum == 0 ? string.Empty : currentMonthPlanMoneyNum.ToString();
                statisticalAnalysisView.CurrentMonthActualCompletedMoneyNum = currentMonthActualCompletedMoneyNum == 0 ? string.Empty : currentMonthActualCompletedMoneyNum.ToString();
                if (!string.IsNullOrEmpty(statisticalAnalysisView.CurrentMonthActualCompletedMoneyNum))
                {
                    if (!string.IsNullOrEmpty(totalMoney))
                    {
                        statisticalAnalysisView.CurrentMonthActualCompletedTotalProportion = Math.Round(Convert.ToDecimal(statisticalAnalysisView.CurrentMonthActualCompletedMoneyNum) * 100 / Convert.ToDecimal(totalMoney), 1).ToString() + "%";
                    }
                    if (!string.IsNullOrEmpty(statisticalAnalysisView.YearPlanMoneyNum))
                    {
                        statisticalAnalysisView.CurrentMonthActualCompletedYearProportion = Math.Round(Convert.ToDecimal(statisticalAnalysisView.CurrentMonthActualCompletedMoneyNum) * 100 / Convert.ToDecimal(statisticalAnalysisView.YearPlanMoneyNum), 1).ToString() + "%";
                    }
                    if (!string.IsNullOrEmpty(statisticalAnalysisView.CurrentMonthPlanMoneyNum))
                    {
                        statisticalAnalysisView.CurrentMonthActualCompletedMonthProportion = Math.Round(Convert.ToDecimal(statisticalAnalysisView.CurrentMonthActualCompletedMoneyNum) * 100 / Convert.ToDecimal(statisticalAnalysisView.CurrentMonthPlanMoneyNum), 1).ToString() + "%";
                    }
                }

                decimal currentYearCumulativeCompletedMoney = 0;
                decimal constructionCompletedMoneyNum = 0;
                GetCumulativeCompletedMoney(projectID, contractType, contractID, year, GetMaxMonth(lstMonth), ref currentYearCumulativeCompletedMoney, ref constructionCompletedMoneyNum);
                statisticalAnalysisView.ConstructionCompletedMoneyNum = constructionCompletedMoneyNum == 0 ? string.Empty : constructionCompletedMoneyNum.ToString();
                if (!string.IsNullOrEmpty(statisticalAnalysisView.ConstructionCompletedMoneyNum))
                {
                    if (!string.IsNullOrEmpty(totalMoney))
                    {
                        statisticalAnalysisView.ConstructionCompletedTotalProportion = Math.Round(Convert.ToDecimal(statisticalAnalysisView.ConstructionCompletedMoneyNum) * 100 / Convert.ToDecimal(totalMoney), 1).ToString() + "%";
                    }
                }
                lstStatisticalAnalysisView.Add(statisticalAnalysisView);
            }
            return lstStatisticalAnalysisView;
        }

        private string GetMonthMoneyFromYearPlanRevise(YearPlanRevise yearPlanRevise, string month)
        {
            string lastMonthMoney = "0";
            if (yearPlanRevise != null)
            {
                switch (month)
                {
                    case "1":
                        lastMonthMoney = yearPlanRevise.JanuaryMoneyNum;
                        break;
                    case "2":
                        lastMonthMoney = yearPlanRevise.FebruaryMoneyNum;
                        break;
                    case "3":
                        lastMonthMoney = yearPlanRevise.MarchMoneyNum;
                        break;
                    case "4":
                        lastMonthMoney = yearPlanRevise.AprilMoneyNum;
                        break;
                    case "5":
                        lastMonthMoney = yearPlanRevise.MayMoneyNum;
                        break;
                    case "6":
                        lastMonthMoney = yearPlanRevise.JuneMoneyNum;
                        break;
                    case "7":
                        lastMonthMoney = yearPlanRevise.JulyMoneyNum;
                        break;
                    case "8":
                        lastMonthMoney = yearPlanRevise.AugustMoneyNum;
                        break;
                    case "9":
                        lastMonthMoney = yearPlanRevise.SeptemberMoneyNum;
                        break;
                    case "10":
                        lastMonthMoney = yearPlanRevise.OctoberMoneyNum;
                        break;
                    case "11":
                        lastMonthMoney = yearPlanRevise.NovemberMoneyNum;
                        break;
                    case "12":
                        lastMonthMoney = yearPlanRevise.DecemberMoneyNum;
                        break;
                }
            }
            return lastMonthMoney;
        }

        public List<StatisticalAnalysisDetailsView> GetStatisticalAnalysisDetailList(Guid projectID, string contractType, string year, List<string> lstMonth, Guid contractID)
        {
            #region 总量维护
            //获取总量维护修订ID
            Guid reviseID = GuidHelper.NewGuid();
            TotalRevise totalRevise = TotalReviseRepository.Entities.Where(t => t.ProjectID == projectID && t.ContractType == contractType && t.ContractID == contractID).OrderByDescending(t => t.ReviseDate).FirstOrDefault();
            if (totalRevise != null)
            {
                reviseID = totalRevise.ID;
            }

            //获取总量维护修订明细
            var queryTotalReviseDetails = from tr in TotalReviseDetailsRepository.Entities
                                          where tr.TotalReviseID == reviseID
                                          select tr;
            #endregion

            #region 年度计划
            //获取年度计划修订ID
            Guid yearPlanReviseID = GuidHelper.NewGuid();
            YearPlanRevise yearPlanRevise = YearPlanReviseRepository.Entities.Where(yr => yr.ProjectID == projectID && yr.ContractType == contractType && yr.ContractID == contractID && yr.StatisticalCycle == year).OrderByDescending(yr => yr.ReviseDate).FirstOrDefault();
            if (yearPlanRevise != null)
            {
                yearPlanReviseID = yearPlanRevise.ID;
            }

            //获取年度计划修订明细
            var queryYearPlanReviseDetails = from yrd in YearPlanReviseDetailsRepository.Entities
                                             where yrd.YearPlanReviseID == yearPlanReviseID
                                             select yrd;
            #endregion

            List<TempModel> lstLastMonthDetail = new List<TempModel>();
            List<MonthPlanDetails> lstMonthPlanDetail = new List<MonthPlanDetails>();
            foreach (string month in lstMonth)
            {
                ////设置当前年月的上一个月
                //string lastYear = string.Empty;
                //string lastMonth = string.Empty;
                //SetLastYearAndMonth(year, month, ref lastYear, ref lastMonth);

                ////获取上月计划明细
                //List<TempModel> lstLastMonthDetailForOneMonth = GetLastMonthDetails(projectID, contractType, contractID, lastYear, lastMonth, yearPlanRevise, month);
                List<TempModel> lstLastMonthDetailForOneMonth = GetMonthDetailsFromYearPlanRevise(yearPlanRevise, month);
                TotalSelectMonthForLastMonthDetail(lstLastMonthDetail, lstLastMonthDetailForOneMonth);

                //获取月度计划明细
                MonthPlan monthPlan = MonthPlanRepository.Entities.SingleOrDefault(m => m.ProjectID == projectID && m.ContractType == contractType && m.ContractID == contractID && m.Year == year && m.Month == month);
                if (monthPlan != null && monthPlan.HandleState == "2")
                {
                    List<MonthPlanDetails> lstMonthPlanDetailForOneMonth = MonthPlanDetailsRepository.Entities.Where(md => md.MonthPlanID == monthPlan.ID).ToList();
                    TotalSelectMonthForMonthPlanDetail(lstMonthPlanDetail, lstMonthPlanDetailForOneMonth);
                }
            }

            //获取本年累计和开工累计
            List<TempModel> lstCurrentYearCumulativeCompleted = new List<TempModel>();
            List<TempModel> lstConstructionCompleted = new List<TempModel>();
            GetCumulativeCompletedDetails(projectID, contractType, contractID, year, GetMaxMonth(lstMonth), lstCurrentYearCumulativeCompleted, lstConstructionCompleted);

            #region 获取连接查询数据
            var queryData = from s in StatisticsItemMaintenanceRepository.Entities.ToList()
                            join td in queryTotalReviseDetails
                            on s.ID equals td.StatisticsItemID into joinedEmpTD
                            from tempTD in joinedEmpTD.DefaultIfEmpty()

                            join yd in queryYearPlanReviseDetails
                            on s.ID equals yd.StatisticsItemID into joinedEmpYD
                            from tempYD in joinedEmpYD.DefaultIfEmpty()

                            join lmd in lstLastMonthDetail
                            on s.ID equals lmd.StatisticsItemID into joinedEmpLMD
                            from tempLMD in joinedEmpLMD.DefaultIfEmpty()

                            join md in lstMonthPlanDetail
                            on s.ID equals md.StatisticsItemID into joinedEmpMD
                            from tempMD in joinedEmpMD.DefaultIfEmpty()

                            join cc in lstConstructionCompleted
                            on s.ID equals cc.StatisticsItemID into joinedEmpCC
                            from tempCC in joinedEmpCC.DefaultIfEmpty()

                            where s.IsParent == false && s.ProjectID == projectID && s.ContractType == contractType
                            orderby s.OrderNo
                            select new
                            {
                                s.StatisticsItemName,
                                s.PID,
                                s.EngineeringUnit,
                                s.MoneyUnit,
                                EngineeringNum = tempTD == null ? string.Empty : tempTD.EngineeringNum,
                                MoneyNum = tempTD == null ? string.Empty : tempTD.MoneyNum,
                                YearPlanEngineeringNum = tempYD == null ? string.Empty : tempYD.TotalEngineeringNum,
                                YearPlanMoneyNum = tempYD == null ? string.Empty : tempYD.TotalMoneyNum,
                                CurrentMonthPlanEngineeringNum = tempLMD == null ? string.Empty : tempLMD.EngineeringNum,
                                CurrentMonthPlanMoneyNum = tempLMD == null ? string.Empty : tempLMD.MoneyNum,
                                ID = tempMD == null ? GuidHelper.NewGuid() : tempMD.ID,
                                CurrentMonthActualCompletedEngineeringNum = tempMD == null ? string.Empty : tempMD.CurrentMonthActualCompletedEngineeringNum,
                                CurrentMonthActualCompletedMoneyNum = tempMD == null ? string.Empty : tempMD.CurrentMonthActualCompletedMoneyNum,
                                ConstructionCompletedEngineeringNum = tempCC == null ? string.Empty : tempCC.EngineeringNum,
                                ConstructionCompletedMoneyNum = tempCC == null ? string.Empty : tempCC.MoneyNum
                            };
            #endregion

            #region 根据连接查询数据设置最后返回列表
            List<StatisticalAnalysisDetailsView> lstStatisticalAnalysisDetailsView = new List<StatisticalAnalysisDetailsView>();
            foreach (var item in queryData)
            {
                string parentStatisticsItemName = item.StatisticsItemName;
                if (item.PID != null)
                {
                    parentStatisticsItemName = GetParentStatisticsItemName(item.PID);
                }

                if (!string.IsNullOrEmpty(item.EngineeringUnit))
                {
                    StatisticalAnalysisDetailsView statisticalAnalysisDetailsView = new StatisticalAnalysisDetailsView();
                    statisticalAnalysisDetailsView.ID = item.ID;
                    statisticalAnalysisDetailsView.StatisticsItemName = item.StatisticsItemName;
                    statisticalAnalysisDetailsView.ParentStatisticsItemName = parentStatisticsItemName;
                    statisticalAnalysisDetailsView.Unit = item.EngineeringUnit;
                    statisticalAnalysisDetailsView.TotalAmount = item.EngineeringNum;
                    statisticalAnalysisDetailsView.YearPlanAmount = item.YearPlanEngineeringNum;
                    statisticalAnalysisDetailsView.CurrentMonthPlanAmount = item.CurrentMonthPlanEngineeringNum;

                    statisticalAnalysisDetailsView.CurrentMonthActualCompletedAmount = item.CurrentMonthActualCompletedEngineeringNum;
                    if (!string.IsNullOrEmpty(item.CurrentMonthActualCompletedEngineeringNum))
                    {
                        statisticalAnalysisDetailsView.CurrentMonthActualCompletedTotalProportion = CountProportion(item.CurrentMonthActualCompletedEngineeringNum, item.EngineeringNum);
                        statisticalAnalysisDetailsView.CurrentMonthActualCompletedYearProportion = CountProportion(item.CurrentMonthActualCompletedEngineeringNum, item.YearPlanEngineeringNum);
                        statisticalAnalysisDetailsView.CurrentMonthActualCompletedMonthProportion = CountProportion(item.CurrentMonthActualCompletedEngineeringNum, item.CurrentMonthPlanEngineeringNum);
                    }

                    statisticalAnalysisDetailsView.ConstructionCompletedAmount = item.ConstructionCompletedEngineeringNum;
                    if (!string.IsNullOrEmpty(item.ConstructionCompletedEngineeringNum))
                    {
                        statisticalAnalysisDetailsView.ConstructionCompletedTotalProportion = CountProportion(item.ConstructionCompletedEngineeringNum, item.EngineeringNum);
                    }

                    lstStatisticalAnalysisDetailsView.Add(statisticalAnalysisDetailsView);
                }

                if (!string.IsNullOrEmpty(item.MoneyUnit))
                {
                    StatisticalAnalysisDetailsView statisticalAnalysisDetailsView = new StatisticalAnalysisDetailsView();
                    statisticalAnalysisDetailsView.ID = item.ID;
                    statisticalAnalysisDetailsView.StatisticsItemName = item.StatisticsItemName;
                    statisticalAnalysisDetailsView.ParentStatisticsItemName = parentStatisticsItemName;
                    statisticalAnalysisDetailsView.Unit = item.MoneyUnit;
                    statisticalAnalysisDetailsView.TotalAmount = item.MoneyNum;
                    statisticalAnalysisDetailsView.YearPlanAmount = item.YearPlanMoneyNum;
                    statisticalAnalysisDetailsView.CurrentMonthPlanAmount = item.CurrentMonthPlanMoneyNum;

                    statisticalAnalysisDetailsView.CurrentMonthActualCompletedAmount = item.CurrentMonthActualCompletedMoneyNum;
                    if (!string.IsNullOrEmpty(item.CurrentMonthActualCompletedMoneyNum))
                    {
                        if (!string.IsNullOrEmpty(item.MoneyNum))
                        {
                            statisticalAnalysisDetailsView.CurrentMonthActualCompletedTotalProportion = Math.Round(Convert.ToDecimal(item.CurrentMonthActualCompletedMoneyNum) * 100 / Convert.ToDecimal(item.MoneyNum), 1).ToString() + "%";
                        }
                        if (!string.IsNullOrEmpty(item.YearPlanMoneyNum))
                        {
                            statisticalAnalysisDetailsView.CurrentMonthActualCompletedYearProportion = Math.Round(Convert.ToDecimal(item.CurrentMonthActualCompletedMoneyNum) * 100 / Convert.ToDecimal(item.YearPlanMoneyNum), 1).ToString() + "%";
                        }
                        if (!string.IsNullOrEmpty(item.CurrentMonthPlanMoneyNum))
                        {
                            statisticalAnalysisDetailsView.CurrentMonthActualCompletedMonthProportion = Math.Round(Convert.ToDecimal(item.CurrentMonthActualCompletedMoneyNum) * 100 / Convert.ToDecimal(item.CurrentMonthPlanMoneyNum), 1).ToString() + "%";
                        }
                    }

                    statisticalAnalysisDetailsView.ConstructionCompletedAmount = item.ConstructionCompletedMoneyNum;
                    if (!string.IsNullOrEmpty(item.ConstructionCompletedMoneyNum))
                    {
                        if (!string.IsNullOrEmpty(item.MoneyNum))
                        {
                            statisticalAnalysisDetailsView.ConstructionCompletedTotalProportion = Math.Round(Convert.ToDecimal(item.ConstructionCompletedMoneyNum) * 100 / Convert.ToDecimal(item.MoneyNum), 1).ToString() + "%";
                        }
                    }

                    lstStatisticalAnalysisDetailsView.Add(statisticalAnalysisDetailsView);
                }
            #endregion
            }
            return lstStatisticalAnalysisDetailsView;
        }

        private List<TempModel> GetMonthDetailsFromYearPlanRevise(YearPlanRevise yearPlanRevise, string month)
        {
            List<TempModel> lstLastMonthDetail = new List<TempModel>();
            if (yearPlanRevise != null)
            {
                IQueryable<YearPlanReviseDetails> lstYearPlanReviseDetail = YearPlanReviseDetailsRepository.Entities.Where(yrd => yrd.YearPlanReviseID == yearPlanRevise.ID);
                foreach (YearPlanReviseDetails yearPlanReviseDetails in lstYearPlanReviseDetail)
                {
                    switch (month)
                    {
                        case "1":
                            lstLastMonthDetail.Add(new TempModel()
                            {
                                StatisticsItemID = yearPlanReviseDetails.StatisticsItemID,
                                EngineeringNum = yearPlanReviseDetails.JanuaryEngineeringNum,
                                MoneyNum = yearPlanReviseDetails.JanuaryMoneyNum
                            });
                            break;
                        case "2":
                            lstLastMonthDetail.Add(new TempModel()
                            {
                                StatisticsItemID = yearPlanReviseDetails.StatisticsItemID,
                                EngineeringNum = yearPlanReviseDetails.FebruaryEngineeringNum,
                                MoneyNum = yearPlanReviseDetails.FebruaryMoneyNum
                            });
                            break;
                        case "3":
                            lstLastMonthDetail.Add(new TempModel()
                            {
                                StatisticsItemID = yearPlanReviseDetails.StatisticsItemID,
                                EngineeringNum = yearPlanReviseDetails.MarchEngineeringNum,
                                MoneyNum = yearPlanReviseDetails.MarchMoneyNum
                            });
                            break;
                        case "4":
                            lstLastMonthDetail.Add(new TempModel()
                            {
                                StatisticsItemID = yearPlanReviseDetails.StatisticsItemID,
                                EngineeringNum = yearPlanReviseDetails.AprilEngineeringNum,
                                MoneyNum = yearPlanReviseDetails.AprilMoneyNum
                            });
                            break;
                        case "5":
                            lstLastMonthDetail.Add(new TempModel()
                            {
                                StatisticsItemID = yearPlanReviseDetails.StatisticsItemID,
                                EngineeringNum = yearPlanReviseDetails.MayEngineeringNum,
                                MoneyNum = yearPlanReviseDetails.MayMoneyNum
                            });
                            break;
                        case "6":
                            lstLastMonthDetail.Add(new TempModel()
                            {
                                StatisticsItemID = yearPlanReviseDetails.StatisticsItemID,
                                EngineeringNum = yearPlanReviseDetails.JuneEngineeringNum,
                                MoneyNum = yearPlanReviseDetails.JuneMoneyNum
                            });
                            break;
                        case "7":
                            lstLastMonthDetail.Add(new TempModel()
                            {
                                StatisticsItemID = yearPlanReviseDetails.StatisticsItemID,
                                EngineeringNum = yearPlanReviseDetails.JulyEngineeringNum,
                                MoneyNum = yearPlanReviseDetails.JulyMoneyNum
                            });
                            break;
                        case "8":
                            lstLastMonthDetail.Add(new TempModel()
                            {
                                StatisticsItemID = yearPlanReviseDetails.StatisticsItemID,
                                EngineeringNum = yearPlanReviseDetails.AugustEngineeringNum,
                                MoneyNum = yearPlanReviseDetails.AugustMoneyNum
                            });
                            break;
                        case "9":
                            lstLastMonthDetail.Add(new TempModel()
                            {
                                StatisticsItemID = yearPlanReviseDetails.StatisticsItemID,
                                EngineeringNum = yearPlanReviseDetails.SeptemberEngineeringNum,
                                MoneyNum = yearPlanReviseDetails.SeptemberMoneyNum
                            });
                            break;
                        case "10":
                            lstLastMonthDetail.Add(new TempModel()
                            {
                                StatisticsItemID = yearPlanReviseDetails.StatisticsItemID,
                                EngineeringNum = yearPlanReviseDetails.OctoberEngineeringNum,
                                MoneyNum = yearPlanReviseDetails.OctoberMoneyNum
                            });
                            break;
                        case "11":
                            lstLastMonthDetail.Add(new TempModel()
                            {
                                StatisticsItemID = yearPlanReviseDetails.StatisticsItemID,
                                EngineeringNum = yearPlanReviseDetails.NovemberEngineeringNum,
                                MoneyNum = yearPlanReviseDetails.NovemberMoneyNum
                            });
                            break;
                        case "12":
                            lstLastMonthDetail.Add(new TempModel()
                            {
                                StatisticsItemID = yearPlanReviseDetails.StatisticsItemID,
                                EngineeringNum = yearPlanReviseDetails.DecemberEngineeringNum,
                                MoneyNum = yearPlanReviseDetails.DecemberMoneyNum
                            });
                            break;
                    }
                }
            }
            return lstLastMonthDetail;
        }
        #endregion

        #region 拨付款 支表二 图表部分里面的月度数据
        public List<PointView> GetMonthPlanComplete(Guid projectID, Guid contractID, double totalReviseMoney, string year, string month)
        {
            List<PointView> lstPointView = new List<PointView>();

            string sql = @"select * from MonthPlans where ProjectID='" + projectID.ToString() + @"' and ContractID='" + contractID + @"' and HandleState='2' and (YEAR<'" + year + @"' or (YEAR='" + year + @"' and Convert(int,MONTH)<CONVERT(int,'" + month + @"'))) order by YEAR,CONVERT(int,month)";
            var lstMonthPlan = DbSqlHelper<MonthPlan>.SqlQueryCommon(sql);
            //List<MonthPlan> lstMonthPlan = MonthPlanRepository.Entities.Where(m => m.ProjectID == projectID && m.ContractID == contractID && m.HandleState == "2" && ((m.Year.CompareTo(year) < 0) || (m.Year == year && m.Month.CompareTo(month) <= 0))).ToList();
            double total = 0;
            int count = 1;
            foreach (MonthPlan monthPlan in lstMonthPlan)
            {
                double reviseMoney = string.IsNullOrEmpty((monthPlan.TotalCurrentMonthActualCompletedMoneyNum as string)) ? 0 : Convert.ToDouble(monthPlan.TotalCurrentMonthActualCompletedMoneyNum);
                total += reviseMoney;
                if (Convert.ToInt32(monthPlan.Year) == 2014)
                {
                    if (count == 1)
                    {
                        AddDictionary(lstPointView, 0, totalReviseMoney, total);
                    }
                    int currentMonth = Convert.ToInt32(monthPlan.Month);
                    AddDictionary(lstPointView, currentMonth, totalReviseMoney, total);
                }
                else if (Convert.ToInt32(monthPlan.Year) == 2015)
                {
                    if (count == 1)
                    {
                        AddDictionary(lstPointView, 0, totalReviseMoney, total);
                    }
                    int currentMonth = Convert.ToInt32(monthPlan.Month) + 12;
                    AddDictionary(lstPointView, currentMonth, totalReviseMoney, total);
                }
                else if (Convert.ToInt32(monthPlan.Year) == 2016)
                {
                    if (count == 1)
                    {
                        AddDictionary(lstPointView, 0, totalReviseMoney, total);
                    }
                    int currentMonth = Convert.ToInt32(monthPlan.Month) + 24;
                    AddDictionary(lstPointView, currentMonth, totalReviseMoney, total);
                }
                count++;
            }

            lstPointView = lstPointView.OrderBy(p => p.X).ToList();
            List<PointView> lstReturnPointView = new List<PointView>();
            for (int i = 0; i < lstPointView.Count; i++)
            {
                lstReturnPointView.Add(new PointView() { X = lstPointView[i].X, Y = lstPointView[i].Y });
                if (i + 1 < lstPointView.Count && lstPointView[i + 1].X > lstPointView[i].X + 1)
                {
                    for (int j = lstPointView[i].X + 1; j < lstPointView[i + 1].X; j++)
                    {
                        lstReturnPointView.Add(new PointView() { X = j, Y = lstPointView[i].Y });
                    }
                }
            }
            return lstReturnPointView;
        }

        private void AddDictionary(List<PointView> lstPointView, int x, double totalReviseMoney, double total)
        {
            double proportion = Math.Round(total / totalReviseMoney * 100, 2);
            lstPointView.Add(new PointView() { X = x, Y = proportion });
        }
        #endregion

        #region 进度查询
        public List<PointView> GetMonthPlanCompleteForMulContract(Guid projectID, string contractType, List<Guid> lstContractID, decimal totalReviseMoney)
        {
            List<PointView> lstPointView = new List<PointView>();

            List<MonthPlan> lstMonthPlan = MonthPlanRepository.Entities.Where(m => m.ProjectID == projectID && m.ContractType == contractType && lstContractID.Contains(m.ContractID) && m.HandleState == "2" && ((m.Year.CompareTo("2017") < 0) || (m.Year == "2017" && m.Month.CompareTo("12") <= 0))).ToList();

            var statisticalCycle = from yp in lstMonthPlan
                                   group yp by new { Year = yp.Year, Month = yp.Month } into temp
                                   orderby temp.Key.Year, Convert.ToInt32(temp.Key.Month) ascending
                                   select new { temp.Key.Year, temp.Key.Month };

            decimal total = 0;
            int count = 1;
            foreach (var key in statisticalCycle)
            {
                List<MonthPlan> lstMonthPlanForYearMonth = lstMonthPlan.Where(m => m.Year == key.Year && m.Month == key.Month).ToList();
                if (lstMonthPlanForYearMonth != null && lstMonthPlanForYearMonth.Count > 0)
                {
                    foreach (MonthPlan monthPlan in lstMonthPlanForYearMonth)
                    {
                        decimal reviseMoney = string.IsNullOrEmpty((monthPlan.TotalCurrentMonthActualCompletedMoneyNum as string)) ? 0 : Convert.ToDecimal(monthPlan.TotalCurrentMonthActualCompletedMoneyNum);
                        total += reviseMoney;
                    }
                    if (Convert.ToInt32(key.Year) == 2014)
                    {
                        if (count == 1)
                        {
                            AddDictionary(lstPointView, 0, totalReviseMoney, total);
                        }
                        int currentMonth = Convert.ToInt32(key.Month);
                        AddDictionary(lstPointView, currentMonth, totalReviseMoney, total);
                    }
                    else if (Convert.ToInt32(key.Year) == 2015)
                    {
                        if (count == 1)
                        {
                            AddDictionary(lstPointView, 0, totalReviseMoney, total);
                        }
                        int currentMonth = Convert.ToInt32(key.Month) + 12;
                        AddDictionary(lstPointView, currentMonth, totalReviseMoney, total);
                    }
                    else if (Convert.ToInt32(key.Year) == 2016)
                    {
                        if (count == 1)
                        {
                            AddDictionary(lstPointView, 0, totalReviseMoney, total);
                        }
                        int currentMonth = Convert.ToInt32(key.Month) + 24;
                        AddDictionary(lstPointView, currentMonth, totalReviseMoney, total);
                    }
                }
                count++;
            }

            return lstPointView;
        }

        private void AddDictionary(List<PointView> lstPointView, int x, decimal totalReviseMoney, decimal total)
        {
            double proportion = (double)Math.Round(total / totalReviseMoney * 100, 2);
            lstPointView.Add(new PointView() { X = x, Y = proportion });
        }
        #endregion
    }
}